home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_400 / 424_01 / ed_157 / regex.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-11-18  |  143.4 KB  |  4,481 lines

  1. /* Extended regular expression matching and search library,
  2.    version 0.12.
  3.    (Implements POSIX draft P10003.2/D11.2, except for
  4.    internationalization features.)
  5.  
  6.    Copyright (C) 1993 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* Modified [21-Mar-1993 09:52:55] by Rush Record,
  23.    removed all DEBUG routines. */
  24.  
  25. /* _AIX requires this to be the first thing in the file. */
  26. #if defined (_AIX) && !defined (REGEX_MALLOC)
  27.   #pragma alloca
  28. #endif
  29.  
  30. #define _GNU_SOURCE
  31.  
  32. /* Modified [21-Mar-1993 09:35:03] by Rush Record, [Nov-93] C. Sandmann */
  33. #include "opsys.h"
  34. #ifdef sparc
  35. #define REGEX_MALLOC
  36. #endif
  37. #ifdef hpux
  38. #define REGEX_MALLOC
  39. #endif
  40. #ifdef sgi
  41. #define REGEX_MALLOC
  42. #endif
  43. #ifdef GNUDOS
  44. #define REGEX_MALLOC
  45. #define STDC_HEADERS 1
  46. #endif
  47.  
  48.  
  49. /* We need this for `regex.h', and perhaps for the Emacs include files.  */
  50. /* Modified [21-Mar-1993 09:41:28]  by Rush Record,
  51.    for VMS CC 3.0. */
  52. #ifdef VMS
  53. #include <types.h>
  54. #define REGEX_MALLOC
  55. #define USG 0
  56. #define __STDC__ 1
  57. #define STDC_HEADERS 1
  58. #else
  59. #include <sys/types.h>
  60. #endif
  61.  
  62. #ifdef HAVE_CONFIG_H
  63. #include "config.h"
  64. #endif
  65.  
  66. /* The `emacs' switch turns on certain matching commands
  67.    that make sense only in Emacs. */
  68. #ifdef emacs
  69.  
  70. #include "lisp.h"
  71. #include "buffer.h"
  72. #include "syntax.h"
  73.  
  74. /* Emacs uses `NULL' as a predicate.  */
  75. #undef NULL
  76.  
  77. #else  /* not emacs */
  78.  
  79. /* We used to test for `BSTRING' here, but only GCC and Emacs define
  80.    `BSTRING', as far as I know, and neither of them use this code.  */
  81. #ifdef VMS
  82. #define HAVE_STRING_H 1
  83. #endif
  84. #if HAVE_STRING_H || STDC_HEADERS
  85. #include <string.h>
  86. #ifndef bcmp
  87. #define bcmp(s1, s2, n)    memcmp ((s1), (s2), (n))
  88. #endif
  89. #ifndef bcopy
  90. #define bcopy(s, d, n)    memcpy ((d), (s), (n))
  91. #endif
  92. #ifndef bzero
  93. #define bzero(s, n)    memset ((s), 0, (n))
  94. #endif
  95. #else
  96. #include <strings.h>
  97. #endif
  98.  
  99. #ifdef STDC_HEADERS
  100. #include <stdlib.h>
  101. #else
  102. char *malloc ();
  103. char *realloc ();
  104. #endif
  105.  
  106.  
  107. /* Define the syntax stuff for \<, \>, etc.  */
  108.  
  109. /* This must be nonzero for the wordchar and notwordchar pattern
  110.    commands in re_match_2.  */
  111. #ifndef Sword 
  112. #define Sword 1
  113. #endif
  114.  
  115. #ifdef SYNTAX_TABLE
  116.  
  117. extern char *re_syntax_table;
  118.  
  119. #else /* not SYNTAX_TABLE */
  120.  
  121. /* How many characters in the character set.  */
  122. #define CHAR_SET_SIZE 256
  123.  
  124. static char re_syntax_table[CHAR_SET_SIZE];
  125.  
  126. static void
  127. init_syntax_once ()
  128. {
  129.    register int c;
  130.    static int done = 0;
  131.  
  132.    if (done)
  133.      return;
  134.  
  135.    bzero (re_syntax_table, sizeof re_syntax_table);
  136.  
  137.    for (c = 'a'; c <= 'z'; c++)
  138.      re_syntax_table[c] = Sword;
  139.  
  140.    for (c = 'A'; c <= 'Z'; c++)
  141.      re_syntax_table[c] = Sword;
  142.  
  143.    for (c = '0'; c <= '9'; c++)
  144.      re_syntax_table[c] = Sword;
  145.  
  146.    re_syntax_table['_'] = Sword;
  147.  
  148.    done = 1;
  149. }
  150.  
  151. #endif /* not SYNTAX_TABLE */
  152.  
  153. #define SYNTAX(c) re_syntax_table[c]
  154.  
  155. #endif /* not emacs */
  156.  
  157. /* Get the interface, including the syntax bits.  */
  158. #include "regex.h"
  159.  
  160. /* isalpha etc. are used for the character classes.  */
  161. /*#include <ctype.h>*/
  162. /* Modified [21-Mar-1993 09:42:34] by Rush Record,
  163.    use our own character type tables. */
  164. /*#include <ctype.h>*/
  165. #include "ctyp_dec.h"
  166. #ifndef isgraph
  167. #define isgraph(c) (isprint (c) && !isspace (c))
  168. #endif
  169. #ifndef isblank
  170. #define isblank(c) ((c) == ' ' || (c) == '\t')
  171. #endif
  172.  
  173. #ifndef isascii
  174. #define isascii(c) 1
  175. #endif
  176.  
  177. #ifdef isblank
  178. #define ISBLANK(c) (isascii (c) && isblank (c))
  179. #else
  180. #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
  181. #endif
  182. #ifdef isgraph
  183. #define ISGRAPH(c) (isascii (c) && isgraph (c))
  184. #else
  185. #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
  186. #endif
  187.  
  188. #define ISPRINT(c) (isascii (c) && isprint (c))
  189. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  190. #define ISALNUM(c) (isascii (c) && isalnum (c))
  191. #define ISALPHA(c) (isascii (c) && isalpha (c))
  192. #define ISCNTRL(c) (isascii (c) && iscntrl (c))
  193. #define ISLOWER(c) (isascii (c) && islower (c))
  194. #define ISPUNCT(c) (isascii (c) && ispunct (c))
  195. #define ISSPACE(c) (isascii (c) && isspace (c))
  196. #define ISUPPER(c) (isascii (c) && isupper (c))
  197. #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
  198.  
  199. #ifndef NULL
  200. #define NULL 0
  201. #endif
  202.  
  203. /* We remove any previous definition of `SIGN_EXTEND_CHAR',
  204.    since ours (we hope) works properly with all combinations of
  205.    machines, compilers, `char' and `unsigned char' argument types.
  206.    (Per Bothner suggested the basic approach.)  */
  207. /* Modified [21-Mar-1993 09:43:24] by Rush Record,
  208.    VMS CC complains about unnecessary undefs. */
  209. #ifndef VMS
  210. #undef SIGN_EXTEND_CHAR
  211. #endif
  212. #if __STDC__
  213. #ifdef VMS
  214. #define SIGN_EXTEND_CHAR(c) ((char) (c))
  215. #else
  216. #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
  217. #endif
  218. #else  /* not __STDC__ */
  219. /* As in Harbison and Steele.  */
  220. #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
  221. #endif
  222.  
  223. /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
  224.    use `alloca' instead of `malloc'.  This is because using malloc in
  225.    re_search* or re_match* could cause memory leaks when C-g is used in
  226.    Emacs; also, malloc is slower and causes storage fragmentation.  On
  227.    the other hand, malloc is more portable, and easier to debug.  
  228.    
  229.    Because we sometimes use alloca, some routines have to be macros,
  230.    not functions -- `alloca'-allocated space disappears at the end of the
  231.    function it is called in.  */
  232.  
  233. #ifdef REGEX_MALLOC
  234.  
  235. #define REGEX_ALLOCATE malloc
  236. /* VMS CC complains about unused macro args, but something must be here. */
  237. #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
  238.  
  239. #else /* not REGEX_MALLOC  */
  240.  
  241. /* Emacs already defines alloca, sometimes.  */
  242. #ifndef alloca
  243.  
  244. /* Make alloca work the best possible way.  */
  245. #ifdef __GNUC__
  246. #define alloca __builtin_alloca
  247. #else /* not __GNUC__ */
  248. #if HAVE_ALLOCA_H
  249. #include <alloca.h>
  250. #else /* not __GNUC__ or HAVE_ALLOCA_H */
  251. #ifndef __AIX /* Already did _AIX, up at the top.  */
  252. char *alloca ();
  253. #endif /* not _AIX */
  254. #endif /* not HAVE_ALLOCA_H */ 
  255. #endif /* not __GNUC__ */
  256.  
  257. #endif /* not alloca */
  258.  
  259. #define REGEX_ALLOCATE alloca
  260.  
  261. /* Assumes a `char *destination' variable.  */
  262. #define REGEX_REALLOCATE(source, osize, nsize)                \
  263.   (destination = (char *) alloca (nsize),                \
  264.    bcopy (source, destination, osize),                    \
  265.    destination)
  266.  
  267. #endif /* not REGEX_MALLOC */
  268.  
  269.  
  270. /* True if `size1' is non-NULL and PTR is pointing anywhere inside
  271.    `string1' or just past its end.  This works if PTR is NULL, which is
  272.    a good thing.  */
  273. #define FIRST_STRING_P(ptr)                     \
  274.   (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  275.  
  276. /* (Re)Allocate N items of type T using malloc, or fail.  */
  277. #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
  278. #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
  279. #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
  280.  
  281. #define BYTEWIDTH 8 /* In bits.  */
  282.  
  283. #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
  284.  
  285. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  286. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  287.  
  288. typedef char boolean;
  289. #define false 0
  290. #define true 1
  291.  
  292. /* These are the command codes that appear in compiled regular
  293.    expressions.  Some opcodes are followed by argument bytes.  A
  294.    command code can specify any interpretation whatsoever for its
  295.    arguments.  Zero bytes may appear in the compiled regular expression.
  296.  
  297.    The value of `exactn' is needed in search.c (search_buffer) in Emacs.
  298.    So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
  299.    `exactn' we use here must also be 1.  */
  300.  
  301. typedef enum
  302. {
  303.   no_op = 0,
  304.  
  305.         /* Followed by one byte giving n, then by n literal bytes.  */
  306.   exactn = 1,
  307.  
  308.         /* Matches any (more or less) character.  */
  309.   anychar,
  310.  
  311.         /* Matches any one char belonging to specified set.  First
  312.            following byte is number of bitmap bytes.  Then come bytes
  313.            for a bitmap saying which chars are in.  Bits in each byte
  314.            are ordered low-bit-first.  A character is in the set if its
  315.            bit is 1.  A character too large to have a bit in the map is
  316.            automatically not in the set.  */
  317.   charset,
  318.  
  319.         /* Same parameters as charset, but match any character that is
  320.            not one of those specified.  */
  321.   charset_not,
  322.  
  323.         /* Start remembering the text that is matched, for storing in a
  324.            register.  Followed by one byte with the register number, in
  325.            the range 0 to one less than the pattern buffer's re_nsub
  326.            field.  Then followed by one byte with the number of groups
  327.            inner to this one.  (This last has to be part of the
  328.            start_memory only because we need it in the on_failure_jump
  329.            of re_match_2.)  */
  330.   start_memory,
  331.  
  332.         /* Stop remembering the text that is matched and store it in a
  333.            memory register.  Followed by one byte with the register
  334.            number, in the range 0 to one less than `re_nsub' in the
  335.            pattern buffer, and one byte with the number of inner groups,
  336.            just like `start_memory'.  (We need the number of inner
  337.            groups here because we don't have any easy way of finding the
  338.            corresponding start_memory when we're at a stop_memory.)  */
  339.   stop_memory,
  340.  
  341.         /* Match a duplicate of something remembered. Followed by one
  342.            byte containing the register number.  */
  343.   duplicate,
  344.  
  345.         /* Fail unless at beginning of line.  */
  346.   begline,
  347.  
  348.         /* Fail unless at end of line.  */
  349.   endline,
  350.  
  351.         /* Succeeds if at beginning of buffer (if emacs) or at beginning
  352.            of string to be matched (if not).  */
  353.   begbuf,
  354.  
  355.         /* Analogously, for end of buffer/string.  */
  356.   endbuf,
  357.  
  358.         /* Followed by two byte relative address to which to jump.  */
  359.   jump, 
  360.  
  361.     /* Same as jump, but marks the end of an alternative.  */
  362.   jump_past_alt,
  363.  
  364.         /* Followed by two-byte relative address of place to resume at
  365.            in case of failure.  */
  366.   on_failure_jump,
  367.     
  368.         /* Like on_failure_jump, but pushes a placeholder instead of the
  369.            current string position when executed.  */
  370.   on_failure_keep_string_jump,
  371.   
  372.         /* Throw away latest failure point and then jump to following
  373.            two-byte relative address.  */
  374.   pop_failure_jump,
  375.  
  376.         /* Change to pop_failure_jump if know won't have to backtrack to
  377.            match; otherwise change to jump.  This is used to jump
  378.            back to the beginning of a repeat.  If what follows this jump
  379.            clearly won't match what the repeat does, such that we can be
  380.            sure that there is no use backtracking out of repetitions
  381.            already matched, then we change it to a pop_failure_jump.
  382.            Followed by two-byte address.  */
  383.   maybe_pop_jump,
  384.  
  385.         /* Jump to following two-byte address, and push a dummy failure
  386.            point. This failure point will be thrown away if an attempt
  387.            is made to use it for a failure.  A `+' construct makes this
  388.            before the first repeat.  Also used as an intermediary kind
  389.            of jump when compiling an alternative.  */
  390.   dummy_failure_jump,
  391.  
  392.     /* Push a dummy failure point and continue.  Used at the end of
  393.        alternatives.  */
  394.   push_dummy_failure,
  395.  
  396.         /* Followed by two-byte relative address and two-byte number n.
  397.            After matching N times, jump to the address upon failure.  */
  398.   succeed_n,
  399.  
  400.         /* Followed by two-byte relative address, and two-byte number n.
  401.            Jump to the address N times, then fail.  */
  402.   jump_n,
  403.  
  404.         /* Set the following two-byte relative address to the
  405.            subsequent two-byte number.  The address *includes* the two
  406.            bytes of number.  */
  407.   set_number_at,
  408.  
  409.   wordchar,    /* Matches any word-constituent character.  */
  410.   notwordchar,    /* Matches any char that is not a word-constituent.  */
  411.  
  412.   wordbeg,    /* Succeeds if at word beginning.  */
  413.   wordend,    /* Succeeds if at word end.  */
  414.  
  415.   wordbound,    /* Succeeds if at a word boundary.  */
  416.   notwordbound    /* Succeeds if not at a word boundary.  */
  417.  
  418. #ifdef emacs
  419.   ,before_dot,    /* Succeeds if before point.  */
  420.   at_dot,    /* Succeeds if at point.  */
  421.   after_dot,    /* Succeeds if after point.  */
  422.  
  423.     /* Matches any character whose syntax is specified.  Followed by
  424.            a byte which contains a syntax code, e.g., Sword.  */
  425.   syntaxspec,
  426.  
  427.     /* Matches any character whose syntax is not that specified.  */
  428.   notsyntaxspec
  429. #endif /* emacs */
  430. } re_opcode_t;
  431.  
  432. /* Common operations on the compiled pattern.  */
  433.  
  434. /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
  435.  
  436. #define STORE_NUMBER(destination, number)                \
  437.   do {                                    \
  438.     (destination)[0] = (number) & 0377;                    \
  439.     (destination)[1] = (number) >> 8;                    \
  440.   } while(0);
  441.  
  442. /* Same as STORE_NUMBER, except increment DESTINATION to
  443.    the byte after where the number is stored.  Therefore, DESTINATION
  444.    must be an lvalue.  */
  445.  
  446. #define STORE_NUMBER_AND_INCR(destination, number)            \
  447.   do {                                    \
  448.     STORE_NUMBER (destination, number);                    \
  449.     (destination) += 2;                            \
  450.   } while(0);
  451.  
  452. /* Put into DESTINATION a number stored in two contiguous bytes starting
  453.    at SOURCE.  */
  454.  
  455. #define EXTRACT_NUMBER(destination, source)                \
  456.   do {                                    \
  457.     (destination) = *(source) & 0377;                    \
  458.     (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;        \
  459.   } while(0);
  460.  
  461.  
  462. /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
  463.    SOURCE must be an lvalue.  */
  464.  
  465. #define EXTRACT_NUMBER_AND_INCR(destination, source)            \
  466.   do {                                    \
  467.     EXTRACT_NUMBER (destination, source);                \
  468.     (source) += 2;                             \
  469.   } while(0);
  470.  
  471.  
  472. /* If DEBUG is defined, Regex prints many voluminous messages about what
  473.    it is doing (if the variable `debug' is nonzero).  If linked with the
  474.    main program in `iregex.c', you can enter patterns and strings
  475.    interactively.  And if linked with the main program in `main.c' and
  476.    the other test files, you can run the already-written tests.  */
  477.  
  478.  
  479. #ifndef VMS
  480. #undef assert
  481. #define assert(e)
  482. #endif
  483.  
  484.  
  485.  
  486. /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
  487.    also be assigned to arbitrarily: each pattern buffer stores its own
  488.    syntax, so it can be changed between regex compilations.  */
  489. reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
  490.  
  491.  
  492. /* Specify the precise syntax of regexps for compilation.  This provides
  493.    for compatibility for various utilities which historically have
  494.    different, incompatible syntaxes.
  495.  
  496.    The argument SYNTAX is a bit mask comprised of the various bits
  497.    defined in regex.h.  We return the old syntax.  */
  498.  
  499. reg_syntax_t
  500. re_set_syntax (syntax)
  501.     reg_syntax_t syntax;
  502. {
  503.   reg_syntax_t ret = re_syntax_options;
  504.   
  505.   re_syntax_options = syntax;
  506.   return ret;
  507. }
  508.  
  509. /* This table gives an error message for each of the error codes listed
  510.    in regex.h.  Obviously the order here has to be same as there.  */
  511.  
  512. static const char *re_error_msg[] =
  513.   { NULL,                    /* REG_NOERROR */
  514.     "No match",                    /* REG_NOMATCH */
  515.     "Invalid regular expression",        /* REG_BADPAT */
  516.     "Invalid collation character",        /* REG_ECOLLATE */
  517.     "Invalid character class name",        /* REG_ECTYPE */
  518.     "Trailing backslash",            /* REG_EESCAPE */
  519.     "Invalid back reference",            /* REG_ESUBREG */
  520.     "Unmatched [ or [^",            /* REG_EBRACK */
  521.     "Unmatched ( or \\(",            /* REG_EPAREN */
  522.     "Unmatched \\{",                /* REG_EBRACE */
  523.     "Invalid content of \\{\\}",        /* REG_BADBR */
  524.     "Invalid range end",            /* REG_ERANGE */
  525.     "Memory exhausted",                /* REG_ESPACE */
  526.     "Invalid preceding regular expression",    /* REG_BADRPT */
  527.     "Premature end of regular expression",    /* REG_EEND */
  528.     "Regular expression too big",        /* REG_ESIZE */
  529.     "Unmatched ) or \\)",            /* REG_ERPAREN */
  530.   };
  531.  
  532. /* Subroutine declarations and macros for regex_compile.  */
  533.  
  534. static void store_op1 (), store_op2 ();
  535. static void insert_op1 (), insert_op2 ();
  536. static boolean at_begline_loc_p (), at_endline_loc_p ();
  537. static boolean group_in_compile_stack ();
  538. static reg_errcode_t compile_range ();
  539.  
  540. /* Fetch the next character in the uncompiled pattern---translating it 
  541.    if necessary.  Also cast from a signed character in the constant
  542.    string passed to us by the user to an unsigned char that we can use
  543.    as an array index (in, e.g., `translate').  */
  544. #define PATFETCH(c)                            \
  545.   do {if (p == pend) return REG_EEND;                    \
  546.     c = (unsigned char) *p++;                        \
  547.     if (translate) c = translate[c];                     \
  548.   } while(0);
  549.  
  550. /* Fetch the next character in the uncompiled pattern, with no
  551.    translation.  */
  552. #define PATFETCH_RAW(c)                            \
  553.   do {if (p == pend) return REG_EEND;                    \
  554.     c = (unsigned char) *p++;                         \
  555.   } while(0);
  556.  
  557. /* Go backwards one character in the pattern.  */
  558. #define PATUNFETCH p--
  559.  
  560.  
  561. /* If `translate' is non-null, return translate[D], else just D.  We
  562.    cast the subscript to translate because some data is declared as
  563.    `char *', to avoid warnings when a string constant is passed.  But
  564.    when we use a character as a subscript we must make it unsigned.  */
  565. #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
  566.  
  567.  
  568. /* Macros for outputting the compiled pattern into `buffer'.  */
  569.  
  570. /* If the buffer isn't allocated when it comes in, use this.  */
  571. #define INIT_BUF_SIZE  32
  572.  
  573. /* Make sure we have at least N more bytes of space in buffer.  */
  574. #define GET_BUFFER_SPACE(n)                        \
  575.     while (b - bufp->buffer + (n) > bufp->allocated)            \
  576.       EXTEND_BUFFER ()
  577.  
  578. /* Make sure we have one more byte of buffer space and then add C to it.  */
  579. #define BUF_PUSH(c)                            \
  580.   do {                                    \
  581.     GET_BUFFER_SPACE (1);                        \
  582.     *b++ = (unsigned char) (c);                        \
  583.   } while(0)
  584.  
  585.  
  586. /* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
  587. #define BUF_PUSH_2(c1, c2)                        \
  588.   do {                                    \
  589.     GET_BUFFER_SPACE (2);                        \
  590.     *b++ = (unsigned char) (c1);                    \
  591.     *b++ = (unsigned char) (c2);                    \
  592.   } while(0)
  593.  
  594.  
  595. /* As with BUF_PUSH_2, except for three bytes.  */
  596. #define BUF_PUSH_3(c1, c2, c3)                        \
  597.   do {                                    \
  598.     GET_BUFFER_SPACE (3);                        \
  599.     *b++ = (unsigned char) (c1);                    \
  600.     *b++ = (unsigned char) (c2);                    \
  601.     *b++ = (unsigned char) (c3);                    \
  602.   } while(0)
  603.  
  604.  
  605. /* Store a jump with opcode OP at LOC to location TO.  We store a
  606.    relative address offset by the three bytes the jump itself occupies.  */
  607. #define STORE_JUMP(op, loc, to) \
  608.   store_op1 (op, loc, (to) - (loc) - 3)
  609.  
  610. /* Likewise, for a two-argument jump.  */
  611. #define STORE_JUMP2(op, loc, to, arg) \
  612.   store_op2 (op, loc, (to) - (loc) - 3, arg)
  613.  
  614. /* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
  615. #define INSERT_JUMP(op, loc, to) \
  616.   insert_op1 (op, loc, (to) - (loc) - 3, b)
  617.  
  618. /* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
  619. #define INSERT_JUMP2(op, loc, to, arg) \
  620.   insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
  621.  
  622.  
  623. /* This is not an arbitrary limit: the arguments which represent offsets
  624.    into the pattern are two bytes long.  So if 2^16 bytes turns out to
  625.    be too small, many things would have to change.  */
  626. #define MAX_BUF_SIZE (1L << 16)
  627.  
  628.  
  629. /* Extend the buffer by twice its current size via realloc and
  630.    reset the pointers that pointed into the old block to point to the
  631.    correct places in the new one.  If extending the buffer results in it
  632.    being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
  633. #define EXTEND_BUFFER()                            \
  634.   do {                                     \
  635.     unsigned char *old_buffer = bufp->buffer;                \
  636.     if (bufp->allocated == MAX_BUF_SIZE)                 \
  637.       return REG_ESIZE;                            \
  638.     bufp->allocated <<= 1;                        \
  639.     if (bufp->allocated > MAX_BUF_SIZE)                    \
  640.       bufp->allocated = MAX_BUF_SIZE;                     \
  641.     bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
  642.     if (bufp->buffer == NULL)                        \
  643.       return REG_ESPACE;                        \
  644.     /* If the buffer moved, move all the pointers into it.  */        \
  645.     if (old_buffer != bufp->buffer)                    \
  646.       {                                    \
  647.         b = (b - old_buffer) + bufp->buffer;                \
  648.         begalt = (begalt - old_buffer) + bufp->buffer;            \
  649.         if (fixup_alt_jump)                        \
  650.           fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
  651.         if (laststart)                            \
  652.           laststart = (laststart - old_buffer) + bufp->buffer;        \
  653.         if (pending_exact)                        \
  654.           pending_exact = (pending_exact - old_buffer) + bufp->buffer;    \
  655.       }                                    \
  656.   } while(0);
  657.  
  658.  
  659. /* Since we have one byte reserved for the register number argument to
  660.    {start,stop}_memory, the maximum number of groups we can report
  661.    things about is what fits in that byte.  */
  662. #define MAX_REGNUM 255
  663.  
  664. /* But patterns can have more than `MAX_REGNUM' registers.  We just
  665.    ignore the excess.  */
  666. typedef unsigned regnum_t;
  667.  
  668.  
  669. /* Macros for the compile stack.  */
  670.  
  671. /* Since offsets can go either forwards or backwards, this type needs to
  672.    be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
  673. typedef int pattern_offset_t;
  674.  
  675. typedef struct
  676. {
  677.   pattern_offset_t begalt_offset;
  678.   pattern_offset_t fixup_alt_jump;
  679.   pattern_offset_t inner_group_offset;
  680.   pattern_offset_t laststart_offset;  
  681.   regnum_t regnum;
  682. } compile_stack_elt_t;
  683.  
  684.  
  685. typedef struct
  686. {
  687.   compile_stack_elt_t *stack;
  688.   unsigned size;
  689.   unsigned avail;            /* Offset of next open position.  */
  690. } compile_stack_type;
  691.  
  692.  
  693. #define INIT_COMPILE_STACK_SIZE 32
  694.  
  695. #define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
  696. #define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
  697.  
  698. /* The next available element.  */
  699. #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
  700.  
  701.  
  702. /* Set the bit for character C in a list.  */
  703. #define SET_LIST_BIT(c)                               \
  704.   (b[((unsigned char) (c)) / BYTEWIDTH]               \
  705.    |= 1 << (((unsigned char) c) % BYTEWIDTH))
  706.  
  707.  
  708. /* Get the next unsigned number in the uncompiled pattern.  */
  709. #define GET_UNSIGNED_NUMBER(num)                     \
  710.   { if (p != pend)                            \
  711.      {                                    \
  712.        PATFETCH (c);                             \
  713.        while (ISDIGIT (c))                         \
  714.          {                                 \
  715.            if (num < 0)                            \
  716.               num = 0;                            \
  717.            num = num * 10 + c - '0';                     \
  718.            if (p == pend)                         \
  719.               break;                             \
  720.            PATFETCH (c);                        \
  721.          }                                 \
  722.        }                                 \
  723.     }        
  724.  
  725. #define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
  726.  
  727. #define IS_CHAR_CLASS(string)                        \
  728.    (STREQ (string, "alpha") || STREQ (string, "upper")            \
  729.     || STREQ (string, "lower") || STREQ (string, "digit")        \
  730.     || STREQ (string, "alnum") || STREQ (string, "xdigit")        \
  731.     || STREQ (string, "space") || STREQ (string, "print")        \
  732.     || STREQ (string, "punct") || STREQ (string, "graph")        \
  733.     || STREQ (string, "cntrl") || STREQ (string, "blank"))
  734.  
  735. /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
  736.    Returns one of error codes defined in `regex.h', or zero for success.
  737.  
  738.    Assumes the `allocated' (and perhaps `buffer') and `translate'
  739.    fields are set in BUFP on entry.
  740.  
  741.    If it succeeds, results are put in BUFP (if it returns an error, the
  742.    contents of BUFP are undefined):
  743.      `buffer' is the compiled pattern;
  744.      `syntax' is set to SYNTAX;
  745.      `used' is set to the length of the compiled pattern;
  746.      `fastmap_accurate' is zero;
  747.      `re_nsub' is the number of subexpressions in PATTERN;
  748.      `not_bol' and `not_eol' are zero;
  749.    
  750.    The `fastmap' and `newline_anchor' fields are neither
  751.    examined nor set.  */
  752.  
  753. static reg_errcode_t
  754. regex_compile (pattern, size, syntax, bufp)
  755.      const char *pattern;
  756.      int size;
  757.      reg_syntax_t syntax;
  758.      struct re_pattern_buffer *bufp;
  759. {
  760.   /* We fetch characters from PATTERN here.  Even though PATTERN is
  761.      `char *' (i.e., signed), we declare these variables as unsigned, so
  762.      they can be reliably used as array indices.  */
  763.   register unsigned char c, c1;
  764.   
  765.   /* A random tempory spot in PATTERN.  */
  766.   const char *p1;
  767.  
  768.   /* Points to the end of the buffer, where we should append.  */
  769.   register unsigned char *b;
  770.   
  771.   /* Keeps track of unclosed groups.  */
  772.   compile_stack_type compile_stack;
  773.  
  774.   /* Points to the current (ending) position in the pattern.  */
  775.   const char *p = pattern;
  776.   const char *pend = pattern + size;
  777.   
  778.   /* How to translate the characters in the pattern.  */
  779.   char *translate = bufp->translate;
  780.  
  781.   /* Address of the count-byte of the most recently inserted `exactn'
  782.      command.  This makes it possible to tell if a new exact-match
  783.      character can be added to that command or if the character requires
  784.      a new `exactn' command.  */
  785.   unsigned char *pending_exact = 0;
  786.  
  787.   /* Address of start of the most recently finished expression.
  788.      This tells, e.g., postfix * where to find the start of its
  789.      operand.  Reset at the beginning of groups and alternatives.  */
  790.   unsigned char *laststart = 0;
  791.  
  792.   /* Address of beginning of regexp, or inside of last group.  */
  793.   unsigned char *begalt;
  794.  
  795.   /* Place in the uncompiled pattern (i.e., the {) to
  796.      which to go back if the interval is invalid.  */
  797.   const char *beg_interval;
  798.                 
  799.   /* Address of the place where a forward jump should go to the end of
  800.      the containing expression.  Each alternative of an `or' -- except the
  801.      last -- ends with a forward jump of this sort.  */
  802.   unsigned char *fixup_alt_jump = 0;
  803.  
  804.   /* Counts open-groups as they are encountered.  Remembered for the
  805.      matching close-group on the compile stack, so the same register
  806.      number is put in the stop_memory as the start_memory.  */
  807.   regnum_t regnum = 0;
  808.  
  809.  
  810.   /* Initialize the compile stack.  */
  811.   compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
  812.   if (compile_stack.stack == NULL)
  813.     return REG_ESPACE;
  814.  
  815.   compile_stack.size = INIT_COMPILE_STACK_SIZE;
  816.   compile_stack.avail = 0;
  817.  
  818.   /* Initialize the pattern buffer.  */
  819.   bufp->syntax = syntax;
  820.   bufp->fastmap_accurate = 0;
  821.   bufp->not_bol = bufp->not_eol = 0;
  822.  
  823.   /* Set `used' to zero, so that if we return an error, the pattern
  824.      printer (for debugging) will think there's no pattern.  We reset it
  825.      at the end.  */
  826.   bufp->used = 0;
  827.   
  828.   /* Always count groups, whether or not bufp->no_sub is set.  */
  829.   bufp->re_nsub = 0;                
  830.  
  831. #if !defined (emacs) && !defined (SYNTAX_TABLE)
  832.   /* Initialize the syntax table.  */
  833.    init_syntax_once ();
  834. #endif
  835.  
  836.   if (bufp->allocated == 0)
  837.     {
  838.       if (bufp->buffer)
  839.     { /* If zero allocated, but buffer is non-null, try to realloc
  840.              enough space.  This loses if buffer's address is bogus, but
  841.              that is the user's responsibility.  */
  842.           RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
  843.         }
  844.       else
  845.         { /* Caller did not allocate a buffer.  Do it for them.  */
  846.           bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
  847.         }
  848.       if (!bufp->buffer) return REG_ESPACE;
  849.  
  850.       bufp->allocated = INIT_BUF_SIZE;
  851.     }
  852.  
  853.   begalt = b = bufp->buffer;
  854.  
  855.   /* Loop through the uncompiled pattern until we're at the end.  */
  856.   while (p != pend)
  857.     {
  858.       PATFETCH (c);
  859.  
  860.       switch (c)
  861.         {
  862.         case '^':
  863.           {
  864.             if (   /* If at start of pattern, it's an operator.  */
  865.                    p == pattern + 1
  866.                    /* If context independent, it's an operator.  */
  867.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  868.                    /* Otherwise, depends on what's come before.  */
  869.                 || at_begline_loc_p (pattern, p, syntax))
  870.               BUF_PUSH (begline);
  871.             else
  872.               goto normal_char;
  873.           }
  874.           break;
  875.  
  876.  
  877.         case '$':
  878.           {
  879.             if (   /* If at end of pattern, it's an operator.  */
  880.                    p == pend 
  881.                    /* If context independent, it's an operator.  */
  882.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  883.                    /* Otherwise, depends on what's next.  */
  884.                 || at_endline_loc_p (p, pend, syntax))
  885.                BUF_PUSH (endline);
  886.              else
  887.                goto normal_char;
  888.            }
  889.            break;
  890.  
  891.  
  892.     case '+':
  893.         case '?':
  894.           if ((syntax & RE_BK_PLUS_QM)
  895.               || (syntax & RE_LIMITED_OPS))
  896.             goto normal_char;
  897.         handle_plus:
  898.         case '*':
  899.           /* If there is no previous pattern... */
  900.           if (!laststart)
  901.             {
  902.               if (syntax & RE_CONTEXT_INVALID_OPS)
  903.                 return REG_BADRPT;
  904.               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  905.                 goto normal_char;
  906.             }
  907.  
  908.           {
  909.             /* Are we optimizing this jump?  */
  910.             boolean keep_string_p = false;
  911.             
  912.             /* 1 means zero (many) matches is allowed.  */
  913.             char zero_times_ok = 0, many_times_ok = 0;
  914.  
  915.             /* If there is a sequence of repetition chars, collapse it
  916.                down to just one (the right one).  We can't combine
  917.                interval operators with these because of, e.g., `a{2}*',
  918.                which should only match an even number of `a's.  */
  919.  
  920.             for (;;)
  921.               {
  922.                 zero_times_ok |= c != '+';
  923.                 many_times_ok |= c != '?';
  924.  
  925.                 if (p == pend)
  926.                   break;
  927.  
  928.                 PATFETCH (c);
  929.  
  930.                 if (c == '*'
  931.                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
  932.                   ;
  933.  
  934.                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
  935.                   {
  936.                     if (p == pend) return REG_EESCAPE;
  937.  
  938.                     PATFETCH (c1);
  939.                     if (!(c1 == '+' || c1 == '?'))
  940.                       {
  941.                         PATUNFETCH;
  942.                         PATUNFETCH;
  943.                         break;
  944.                       }
  945.  
  946.                     c = c1;
  947.                   }
  948.                 else
  949.                   {
  950.                     PATUNFETCH;
  951.                     break;
  952.                   }
  953.  
  954.                 /* If we get here, we found another repeat character.  */
  955.                }
  956.  
  957.             /* Star, etc. applied to an empty pattern is equivalent
  958.                to an empty pattern.  */
  959.             if (!laststart)  
  960.               break;
  961.  
  962.             /* Now we know whether or not zero matches is allowed
  963.                and also whether or not two or more matches is allowed.  */
  964.             if (many_times_ok)
  965.               { /* More than one repetition is allowed, so put in at the
  966.                    end a backward relative jump from `b' to before the next
  967.                    jump we're going to put in below (which jumps from
  968.                    laststart to after this jump).  
  969.  
  970.                    But if we are at the `*' in the exact sequence `.*\n',
  971.                    insert an unconditional jump backwards to the .,
  972.                    instead of the beginning of the loop.  This way we only
  973.                    push a failure point once, instead of every time
  974.                    through the loop.  */
  975. /*                assert (p - 1 > pattern);*/
  976.  
  977.                 /* Allocate the space for the jump.  */
  978.                 GET_BUFFER_SPACE (3);
  979.  
  980.                 /* We know we are not at the first character of the pattern,
  981.                    because laststart was nonzero.  And we've already
  982.                    incremented `p', by the way, to be the character after
  983.                    the `*'.  Do we have to do something analogous here
  984.                    for null bytes, because of RE_DOT_NOT_NULL?  */
  985.                 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
  986.             && zero_times_ok
  987.                     && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
  988.                     && !(syntax & RE_DOT_NEWLINE))
  989.                   { /* We have .*\n.  */
  990.                     STORE_JUMP (jump, b, laststart);
  991.                     keep_string_p = true;
  992.                   }
  993.                 else
  994.                   /* Anything else.  */
  995.                   STORE_JUMP (maybe_pop_jump, b, laststart - 3);
  996.  
  997.                 /* We've added more stuff to the buffer.  */
  998.                 b += 3;
  999.               }
  1000.  
  1001.             /* On failure, jump from laststart to b + 3, which will be the
  1002.                end of the buffer after this jump is inserted.  */
  1003.             GET_BUFFER_SPACE (3);
  1004.             INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
  1005.                                        : on_failure_jump,
  1006.                          laststart, b + 3);
  1007.             pending_exact = 0;
  1008.             b += 3;
  1009.  
  1010.             if (!zero_times_ok)
  1011.               {
  1012.                 /* At least one repetition is required, so insert a
  1013.                    `dummy_failure_jump' before the initial
  1014.                    `on_failure_jump' instruction of the loop. This
  1015.                    effects a skip over that instruction the first time
  1016.                    we hit that loop.  */
  1017.                 GET_BUFFER_SPACE (3);
  1018.                 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
  1019.                 b += 3;
  1020.               }
  1021.             }
  1022.       break;
  1023.  
  1024.  
  1025.     case '.':
  1026.           laststart = b;
  1027.           BUF_PUSH (anychar);
  1028.           break;
  1029.  
  1030.  
  1031.         case '[':
  1032.           {
  1033.             boolean had_char_class = false;
  1034.  
  1035.             if (p == pend) return REG_EBRACK;
  1036.  
  1037.             /* Ensure that we have enough space to push a charset: the
  1038.                opcode, the length count, and the bitset; 34 bytes in all.  */
  1039.         GET_BUFFER_SPACE (34);
  1040.  
  1041.             laststart = b;
  1042.  
  1043.             /* We test `*p == '^' twice, instead of using an if
  1044.                statement, so we only need one BUF_PUSH.  */
  1045.             BUF_PUSH (*p == '^' ? charset_not : charset); 
  1046.             if (*p == '^')
  1047.               p++;
  1048.  
  1049.             /* Remember the first position in the bracket expression.  */
  1050.             p1 = p;
  1051.  
  1052.             /* Push the number of bytes in the bitmap.  */
  1053.             BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  1054.  
  1055.             /* Clear the whole map.  */
  1056.             bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  1057.  
  1058.             /* charset_not matches newline according to a syntax bit.  */
  1059.             if ((re_opcode_t) b[-2] == charset_not
  1060.                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
  1061.               SET_LIST_BIT ('\n');
  1062.  
  1063.             /* Read in characters and ranges, setting map bits.  */
  1064.             for (;;)
  1065.               {
  1066.                 if (p == pend) return REG_EBRACK;
  1067.  
  1068.                 PATFETCH (c);
  1069.  
  1070.                 /* \ might escape characters inside [...] and [^...].  */
  1071.                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
  1072.                   {
  1073.                     if (p == pend) return REG_EESCAPE;
  1074.  
  1075.                     PATFETCH (c1);
  1076.                     SET_LIST_BIT (c1);
  1077.                     continue;
  1078.                   }
  1079.  
  1080.                 /* Could be the end of the bracket expression.  If it's
  1081.                    not (i.e., when the bracket expression is `[]' so
  1082.                    far), the ']' character bit gets set way below.  */
  1083.                 if (c == ']' && p != p1 + 1)
  1084.                   break;
  1085.  
  1086.                 /* Look ahead to see if it's a range when the last thing
  1087.                    was a character class.  */
  1088.                 if (had_char_class && c == '-' && *p != ']')
  1089.                   return REG_ERANGE;
  1090.  
  1091.                 /* Look ahead to see if it's a range when the last thing
  1092.                    was a character: if this is a hyphen not at the
  1093.                    beginning or the end of a list, then it's the range
  1094.                    operator.  */
  1095.                 if (c == '-' 
  1096.                     && !(p - 2 >= pattern && p[-2] == '[') 
  1097.                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
  1098.                     && *p != ']')
  1099.                   {
  1100.                     reg_errcode_t ret
  1101.                       = compile_range (&p, pend, translate, syntax, b);
  1102.                     if (ret != REG_NOERROR) return ret;
  1103.                   }
  1104.  
  1105.                 else if (p[0] == '-' && p[1] != ']')
  1106.                   { /* This handles ranges made up of characters only.  */
  1107.                     reg_errcode_t ret;
  1108.  
  1109.             /* Move past the `-'.  */
  1110.                     PATFETCH (c1);
  1111.                     
  1112.                     ret = compile_range (&p, pend, translate, syntax, b);
  1113.                     if (ret != REG_NOERROR) return ret;
  1114.                   }
  1115.  
  1116.                 /* See if we're at the beginning of a possible character
  1117.                    class.  */
  1118.  
  1119.                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
  1120.                   { /* Leave room for the null.  */
  1121.                     char str[CHAR_CLASS_MAX_LENGTH + 1];
  1122.  
  1123.                     PATFETCH (c);
  1124.                     c1 = 0;
  1125.  
  1126.                     /* If pattern is `[[:'.  */
  1127.                     if (p == pend) return REG_EBRACK;
  1128.  
  1129.                     for (;;)
  1130.                       {
  1131.                         PATFETCH (c);
  1132.                         if (c == ':' || c == ']' || p == pend
  1133.                             || c1 == CHAR_CLASS_MAX_LENGTH)
  1134.                           break;
  1135.                         str[c1++] = c;
  1136.                       }
  1137.                     str[c1] = '\0';
  1138.  
  1139.                     /* If isn't a word bracketed by `[:' and:`]':
  1140.                        undo the ending character, the letters, and leave 
  1141.                        the leading `:' and `[' (but set bits for them).  */
  1142.                     if (c == ':' && *p == ']')
  1143.                       {
  1144.                         int ch;
  1145.                         boolean is_alnum = STREQ (str, "alnum");
  1146.                         boolean is_alpha = STREQ (str, "alpha");
  1147.                         boolean is_blank = STREQ (str, "blank");
  1148.                         boolean is_cntrl = STREQ (str, "cntrl");
  1149.                         boolean is_digit = STREQ (str, "digit");
  1150.                         boolean is_graph = STREQ (str, "graph");
  1151.                         boolean is_lower = STREQ (str, "lower");
  1152.                         boolean is_print = STREQ (str, "print");
  1153.                         boolean is_punct = STREQ (str, "punct");
  1154.                         boolean is_space = STREQ (str, "space");
  1155.                         boolean is_upper = STREQ (str, "upper");
  1156.                         boolean is_xdigit = STREQ (str, "xdigit");
  1157.                         
  1158.                         if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
  1159.  
  1160.                         /* Throw away the ] at the end of the character
  1161.                            class.  */
  1162.                         PATFETCH (c);                    
  1163.  
  1164.                         if (p == pend) return REG_EBRACK;
  1165.  
  1166.                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
  1167.                           {
  1168.                             if (   (is_alnum  && ISALNUM (ch))
  1169.                                 || (is_alpha  && ISALPHA (ch))
  1170.                                 || (is_blank  && ISBLANK (ch))
  1171.                                 || (is_cntrl  && ISCNTRL (ch))
  1172.                                 || (is_digit  && ISDIGIT (ch))
  1173.                                 || (is_graph  && ISGRAPH (ch))
  1174.                                 || (is_lower  && ISLOWER (ch))
  1175.                                 || (is_print  && ISPRINT (ch))
  1176.                                 || (is_punct  && ISPUNCT (ch))
  1177.                                 || (is_space  && ISSPACE (ch))
  1178.                                 || (is_upper  && ISUPPER (ch))
  1179.                                 || (is_xdigit && ISXDIGIT (ch)))
  1180.                             SET_LIST_BIT (ch);
  1181.                           }
  1182.                         had_char_class = true;
  1183.                       }
  1184.                     else
  1185.                       {
  1186.                         c1++;
  1187.                         while (c1--)    
  1188.                           PATUNFETCH;
  1189.                         SET_LIST_BIT ('[');
  1190.                         SET_LIST_BIT (':');
  1191.                         had_char_class = false;
  1192.                       }
  1193.                   }
  1194.                 else
  1195.                   {
  1196.                     had_char_class = false;
  1197.                     SET_LIST_BIT (c);
  1198.                   }
  1199.               }
  1200.  
  1201.             /* Discard any (non)matching list bytes that are all 0 at the
  1202.                end of the map.  Decrease the map-length byte too.  */
  1203.             while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
  1204.               b[-1]--; 
  1205.             b += b[-1];
  1206.           }
  1207.           break;
  1208.  
  1209.  
  1210.     case '(':
  1211.           if (syntax & RE_NO_BK_PARENS)
  1212.             goto handle_open;
  1213.           else
  1214.             goto normal_char;
  1215.  
  1216.  
  1217.         case ')':
  1218.           if (syntax & RE_NO_BK_PARENS)
  1219.             goto handle_close;
  1220.           else
  1221.             goto normal_char;
  1222.  
  1223.  
  1224.         case '\n':
  1225.           if (syntax & RE_NEWLINE_ALT)
  1226.             goto handle_alt;
  1227.           else
  1228.             goto normal_char;
  1229.  
  1230.  
  1231.     case '|':
  1232.           if (syntax & RE_NO_BK_VBAR)
  1233.             goto handle_alt;
  1234.           else
  1235.             goto normal_char;
  1236.  
  1237.  
  1238.         case '{':
  1239.            if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
  1240.              goto handle_interval;
  1241.            else
  1242.              goto normal_char;
  1243.  
  1244.  
  1245.         case '\\':
  1246.           if (p == pend) return REG_EESCAPE;
  1247.  
  1248.           /* Do not translate the character after the \, so that we can
  1249.              distinguish, e.g., \B from \b, even if we normally would
  1250.              translate, e.g., B to b.  */
  1251.           PATFETCH_RAW (c);
  1252.  
  1253.           switch (c)
  1254.             {
  1255.             case '(':
  1256.               if (syntax & RE_NO_BK_PARENS)
  1257.                 goto normal_backslash;
  1258.  
  1259.             handle_open:
  1260.               bufp->re_nsub++;
  1261.               regnum++;
  1262.  
  1263.               if (COMPILE_STACK_FULL)
  1264.                 { 
  1265.                   RETALLOC (compile_stack.stack, compile_stack.size << 1,
  1266.                             compile_stack_elt_t);
  1267.                   if (compile_stack.stack == NULL) return REG_ESPACE;
  1268.  
  1269.                   compile_stack.size <<= 1;
  1270.                 }
  1271.  
  1272.               /* These are the values to restore when we hit end of this
  1273.                  group.  They are all relative offsets, so that if the
  1274.                  whole pattern moves because of realloc, they will still
  1275.                  be valid.  */
  1276.               COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
  1277.               COMPILE_STACK_TOP.fixup_alt_jump 
  1278.                 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
  1279.               COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
  1280.               COMPILE_STACK_TOP.regnum = regnum;
  1281.  
  1282.               /* We will eventually replace the 0 with the number of
  1283.                  groups inner to this one.  But do not push a
  1284.                  start_memory for groups beyond the last one we can
  1285.                  represent in the compiled pattern.  */
  1286.               if (regnum <= MAX_REGNUM)
  1287.                 {
  1288.                   COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
  1289.                   BUF_PUSH_3 (start_memory, regnum, 0);
  1290.                 }
  1291.                 
  1292.               compile_stack.avail++;
  1293.  
  1294.               fixup_alt_jump = 0;
  1295.               laststart = 0;
  1296.               begalt = b;
  1297.           /* If we've reached MAX_REGNUM groups, then this open
  1298.          won't actually generate any code, so we'll have to
  1299.          clear pending_exact explicitly.  */
  1300.           pending_exact = 0;
  1301.               break;
  1302.  
  1303.  
  1304.             case ')':
  1305.               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
  1306.  
  1307.               if (COMPILE_STACK_EMPTY)
  1308.                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1309.                   goto normal_backslash;
  1310.                 else
  1311.                   return REG_ERPAREN;
  1312.  
  1313.             handle_close:
  1314.               if (fixup_alt_jump)
  1315.                 { /* Push a dummy failure point at the end of the
  1316.                      alternative for a possible future
  1317.                      `pop_failure_jump' to pop.  See comments at
  1318.                      `push_dummy_failure' in `re_match_2'.  */
  1319.                   BUF_PUSH (push_dummy_failure);
  1320.                   
  1321.                   /* We allocated space for this jump when we assigned
  1322.                      to `fixup_alt_jump', in the `handle_alt' case below.  */
  1323.                   STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
  1324.                 }
  1325.  
  1326.               /* See similar code for backslashed left paren above.  */
  1327.               if (COMPILE_STACK_EMPTY)
  1328.                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1329.                   goto normal_char;
  1330.                 else
  1331.                   return REG_ERPAREN;
  1332.  
  1333.               /* Since we just checked for an empty stack above, this
  1334.                  ``can't happen''.  */
  1335. /*              assert (compile_stack.avail != 0);*/
  1336.               {
  1337.                 /* We don't just want to restore into `regnum', because
  1338.                    later groups should continue to be numbered higher,
  1339.                    as in `(ab)c(de)' -- the second group is #2.  */
  1340.                 regnum_t this_group_regnum;
  1341.  
  1342.                 compile_stack.avail--;        
  1343.                 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
  1344.                 fixup_alt_jump
  1345.                   = COMPILE_STACK_TOP.fixup_alt_jump
  1346.                     ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 
  1347.                     : 0;
  1348.                 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
  1349.                 this_group_regnum = COMPILE_STACK_TOP.regnum;
  1350.         /* If we've reached MAX_REGNUM groups, then this open
  1351.            won't actually generate any code, so we'll have to
  1352.            clear pending_exact explicitly.  */
  1353.         pending_exact = 0;
  1354.  
  1355.                 /* We're at the end of the group, so now we know how many
  1356.                    groups were inside this one.  */
  1357.                 if (this_group_regnum <= MAX_REGNUM)
  1358.                   {
  1359.                     unsigned char *inner_group_loc
  1360.                       = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
  1361.                     
  1362.                     *inner_group_loc = regnum - this_group_regnum;
  1363.                     BUF_PUSH_3 (stop_memory, this_group_regnum,
  1364.                                 regnum - this_group_regnum);
  1365.                   }
  1366.               }
  1367.               break;
  1368.  
  1369.  
  1370.             case '|':                    /* `\|'.  */
  1371.               if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
  1372.                 goto normal_backslash;
  1373.             handle_alt:
  1374.               if (syntax & RE_LIMITED_OPS)
  1375.                 goto normal_char;
  1376.  
  1377.               /* Insert before the previous alternative a jump which
  1378.                  jumps to this alternative if the former fails.  */
  1379.               GET_BUFFER_SPACE (3);
  1380.               INSERT_JUMP (on_failure_jump, begalt, b + 6);
  1381.               pending_exact = 0;
  1382.               b += 3;
  1383.  
  1384.               /* The alternative before this one has a jump after it
  1385.                  which gets executed if it gets matched.  Adjust that
  1386.                  jump so it will jump to this alternative's analogous
  1387.                  jump (put in below, which in turn will jump to the next
  1388.                  (if any) alternative's such jump, etc.).  The last such
  1389.                  jump jumps to the correct final destination.  A picture:
  1390.                           _____ _____ 
  1391.                           |   | |   |   
  1392.                           |   v |   v 
  1393.                          a | b   | c   
  1394.  
  1395.                  If we are at `b', then fixup_alt_jump right now points to a
  1396.                  three-byte space after `a'.  We'll put in the jump, set
  1397.                  fixup_alt_jump to right after `b', and leave behind three
  1398.                  bytes which we'll fill in when we get to after `c'.  */
  1399.  
  1400.               if (fixup_alt_jump)
  1401.                 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  1402.  
  1403.               /* Mark and leave space for a jump after this alternative,
  1404.                  to be filled in later either by next alternative or
  1405.                  when know we're at the end of a series of alternatives.  */
  1406.               fixup_alt_jump = b;
  1407.               GET_BUFFER_SPACE (3);
  1408.               b += 3;
  1409.  
  1410.               laststart = 0;
  1411.               begalt = b;
  1412.               break;
  1413.  
  1414.  
  1415.             case '{': 
  1416.               /* If \{ is a literal.  */
  1417.               if (!(syntax & RE_INTERVALS)
  1418.                      /* If we're at `\{' and it's not the open-interval 
  1419.                         operator.  */
  1420.                   || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1421.                   || (p - 2 == pattern  &&  p == pend))
  1422.                 goto normal_backslash;
  1423.  
  1424.             handle_interval:
  1425.               {
  1426.                 /* If got here, then the syntax allows intervals.  */
  1427.  
  1428.                 /* At least (most) this many matches must be made.  */
  1429.                 int lower_bound = -1, upper_bound = -1;
  1430.  
  1431.                 beg_interval = p - 1;
  1432.  
  1433.                 if (p == pend)
  1434.                   {
  1435.                     if (syntax & RE_NO_BK_BRACES)
  1436.                       goto unfetch_interval;
  1437.                     else
  1438.                       return REG_EBRACE;
  1439.                   }
  1440.  
  1441.                 GET_UNSIGNED_NUMBER (lower_bound);
  1442.  
  1443.                 if (c == ',')
  1444.                   {
  1445.                     GET_UNSIGNED_NUMBER (upper_bound);
  1446.                     if (upper_bound < 0) upper_bound = RE_DUP_MAX;
  1447.                   }
  1448.                 else
  1449.                   /* Interval such as `{1}' => match exactly once. */
  1450.                   upper_bound = lower_bound;
  1451.  
  1452.                 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
  1453.                     || lower_bound > upper_bound)
  1454.                   {
  1455.                     if (syntax & RE_NO_BK_BRACES)
  1456.                       goto unfetch_interval;
  1457.                     else 
  1458.                       return REG_BADBR;
  1459.                   }
  1460.  
  1461.                 if (!(syntax & RE_NO_BK_BRACES)) 
  1462.                   {
  1463.                     if (c != '\\') return REG_EBRACE;
  1464.  
  1465.                     PATFETCH (c);
  1466.                   }
  1467.  
  1468.                 if (c != '}')
  1469.                   {
  1470.                     if (syntax & RE_NO_BK_BRACES)
  1471.                       goto unfetch_interval;
  1472.                     else 
  1473.                       return REG_BADBR;
  1474.                   }
  1475.  
  1476.                 /* We just parsed a valid interval.  */
  1477.  
  1478.                 /* If it's invalid to have no preceding re.  */
  1479.                 if (!laststart)
  1480.                   {
  1481.                     if (syntax & RE_CONTEXT_INVALID_OPS)
  1482.                       return REG_BADRPT;
  1483.                     else if (syntax & RE_CONTEXT_INDEP_OPS)
  1484.                       laststart = b;
  1485.                     else
  1486.                       goto unfetch_interval;
  1487.                   }
  1488.  
  1489.                 /* If the upper bound is zero, don't want to succeed at
  1490.                    all; jump from `laststart' to `b + 3', which will be
  1491.                    the end of the buffer after we insert the jump.  */
  1492.                  if (upper_bound == 0)
  1493.                    {
  1494.                      GET_BUFFER_SPACE (3);
  1495.                      INSERT_JUMP (jump, laststart, b + 3);
  1496.                      b += 3;
  1497.                    }
  1498.  
  1499.                  /* Otherwise, we have a nontrivial interval.  When
  1500.                     we're all done, the pattern will look like:
  1501.                       set_number_at <jump count> <upper bound>
  1502.                       set_number_at <succeed_n count> <lower bound>
  1503.                       succeed_n <after jump addr> <succed_n count>
  1504.                       <body of loop>
  1505.                       jump_n <succeed_n addr> <jump count>
  1506.                     (The upper bound and `jump_n' are omitted if
  1507.                     `upper_bound' is 1, though.)  */
  1508.                  else 
  1509.                    { /* If the upper bound is > 1, we need to insert
  1510.                         more at the end of the loop.  */
  1511.                      unsigned nbytes = 10 + (upper_bound > 1) * 10;
  1512.  
  1513.                      GET_BUFFER_SPACE (nbytes);
  1514.  
  1515.                      /* Initialize lower bound of the `succeed_n', even
  1516.                         though it will be set during matching by its
  1517.                         attendant `set_number_at' (inserted next),
  1518.                         because `re_compile_fastmap' needs to know.
  1519.                         Jump to the `jump_n' we might insert below.  */
  1520.                      INSERT_JUMP2 (succeed_n, laststart,
  1521.                                    b + 5 + (upper_bound > 1) * 5,
  1522.                                    lower_bound);
  1523.                      b += 5;
  1524.  
  1525.                      /* Code to initialize the lower bound.  Insert 
  1526.                         before the `succeed_n'.  The `5' is the last two
  1527.                         bytes of this `set_number_at', plus 3 bytes of
  1528.                         the following `succeed_n'.  */
  1529.                      insert_op2 (set_number_at, laststart, 5, lower_bound, b);
  1530.                      b += 5;
  1531.  
  1532.                      if (upper_bound > 1)
  1533.                        { /* More than one repetition is allowed, so
  1534.                             append a backward jump to the `succeed_n'
  1535.                             that starts this interval.
  1536.                             
  1537.                             When we've reached this during matching,
  1538.                             we'll have matched the interval once, so
  1539.                             jump back only `upper_bound - 1' times.  */
  1540.                          STORE_JUMP2 (jump_n, b, laststart + 5,
  1541.                                       upper_bound - 1);
  1542.                          b += 5;
  1543.  
  1544.                          /* The location we want to set is the second
  1545.                             parameter of the `jump_n'; that is `b-2' as
  1546.                             an absolute address.  `laststart' will be
  1547.                             the `set_number_at' we're about to insert;
  1548.                             `laststart+3' the number to set, the source
  1549.                             for the relative address.  But we are
  1550.                             inserting into the middle of the pattern --
  1551.                             so everything is getting moved up by 5.
  1552.                             Conclusion: (b - 2) - (laststart + 3) + 5,
  1553.                             i.e., b - laststart.
  1554.                             
  1555.                             We insert this at the beginning of the loop
  1556.                             so that if we fail during matching, we'll
  1557.                             reinitialize the bounds.  */
  1558.                          insert_op2 (set_number_at, laststart, b - laststart,
  1559.                                      upper_bound - 1, b);
  1560.                          b += 5;
  1561.                        }
  1562.                    }
  1563.                 pending_exact = 0;
  1564.                 beg_interval = NULL;
  1565.               }
  1566.               break;
  1567.  
  1568.             unfetch_interval:
  1569.               /* If an invalid interval, match the characters as literals.  */
  1570. /*               assert (beg_interval);*/
  1571.                p = beg_interval;
  1572.                beg_interval = NULL;
  1573.  
  1574.                /* normal_char and normal_backslash need `c'.  */
  1575.                PATFETCH (c);    
  1576.  
  1577.                if (!(syntax & RE_NO_BK_BRACES))
  1578.                  {
  1579.                    if (p > pattern  &&  p[-1] == '\\')
  1580.                      goto normal_backslash;
  1581.                  }
  1582.                goto normal_char;
  1583.  
  1584. #ifdef emacs
  1585.             /* There is no way to specify the before_dot and after_dot
  1586.                operators.  rms says this is ok.  --karl  */
  1587.             case '=':
  1588.               BUF_PUSH (at_dot);
  1589.               break;
  1590.  
  1591.             case 's':    
  1592.               laststart = b;
  1593.               PATFETCH (c);
  1594.               BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
  1595.               break;
  1596.  
  1597.             case 'S':
  1598.               laststart = b;
  1599.               PATFETCH (c);
  1600.               BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
  1601.               break;
  1602. #endif /* emacs */
  1603.  
  1604.  
  1605.             case 'w':
  1606.               laststart = b;
  1607.               BUF_PUSH (wordchar);
  1608.               break;
  1609.  
  1610.  
  1611.             case 'W':
  1612.               laststart = b;
  1613.               BUF_PUSH (notwordchar);
  1614.               break;
  1615.  
  1616.  
  1617.             case '<':
  1618.               BUF_PUSH (wordbeg);
  1619.               break;
  1620.  
  1621.             case '>':
  1622.               BUF_PUSH (wordend);
  1623.               break;
  1624.  
  1625.             case 'b':
  1626.               BUF_PUSH (wordbound);
  1627.               break;
  1628.  
  1629.             case 'B':
  1630.               BUF_PUSH (notwordbound);
  1631.               break;
  1632.  
  1633.             case '`':
  1634.               BUF_PUSH (begbuf);
  1635.               break;
  1636.  
  1637.             case '\'':
  1638.               BUF_PUSH (endbuf);
  1639.               break;
  1640.  
  1641.             case '1': case '2': case '3': case '4': case '5':
  1642.             case '6': case '7': case '8': case '9':
  1643.               if (syntax & RE_NO_BK_REFS)
  1644.                 goto normal_char;
  1645.  
  1646.               c1 = c - '0';
  1647.  
  1648.               if (c1 > regnum)
  1649.                 return REG_ESUBREG;
  1650.  
  1651.               /* Can't back reference to a subexpression if inside of it.  */
  1652.               if (group_in_compile_stack (compile_stack, c1))
  1653.                 goto normal_char;
  1654.  
  1655.               laststart = b;
  1656.               BUF_PUSH_2 (duplicate, c1);
  1657.               break;
  1658.  
  1659.  
  1660.             case '+':
  1661.             case '?':
  1662.               if (syntax & RE_BK_PLUS_QM)
  1663.                 goto handle_plus;
  1664.               else
  1665.                 goto normal_backslash;
  1666.  
  1667.             default:
  1668.             normal_backslash:
  1669.               /* You might think it would be useful for \ to mean
  1670.                  not to translate; but if we don't translate it
  1671.                  it will never match anything.  */
  1672.               c = TRANSLATE (c);
  1673.               goto normal_char;
  1674.             }
  1675.           break;
  1676.  
  1677.  
  1678.     default:
  1679.         /* Expects the character in `c'.  */
  1680.     normal_char:
  1681.           /* If no exactn currently being built.  */
  1682.           if (!pending_exact 
  1683.  
  1684.               /* If last exactn not at current position.  */
  1685.               || pending_exact + *pending_exact + 1 != b
  1686.               
  1687.               /* We have only one byte following the exactn for the count.  */
  1688.           || *pending_exact == (1 << BYTEWIDTH) - 1
  1689.  
  1690.               /* If followed by a repetition operator.  */
  1691.               || *p == '*' || *p == '^'
  1692.           || ((syntax & RE_BK_PLUS_QM)
  1693.           ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  1694.           : (*p == '+' || *p == '?'))
  1695.           || ((syntax & RE_INTERVALS)
  1696.                   && ((syntax & RE_NO_BK_BRACES)
  1697.               ? *p == '{'
  1698.                       : (p[0] == '\\' && p[1] == '{'))))
  1699.         {
  1700.           /* Start building a new exactn.  */
  1701.               
  1702.               laststart = b;
  1703.  
  1704.           BUF_PUSH_2 (exactn, 0);
  1705.           pending_exact = b - 1;
  1706.             }
  1707.             
  1708.       BUF_PUSH (c);
  1709.           (*pending_exact)++;
  1710.       break;
  1711.         } /* switch (c) */
  1712.     } /* while p != pend */
  1713.  
  1714.   
  1715.   /* Through the pattern now.  */
  1716.   
  1717.   if (fixup_alt_jump)
  1718.     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  1719.  
  1720.   if (!COMPILE_STACK_EMPTY) 
  1721.     return REG_EPAREN;
  1722.  
  1723.   free (compile_stack.stack);
  1724.  
  1725.   /* We have succeeded; set the length of the buffer.  */
  1726.   bufp->used = b - bufp->buffer;
  1727.  
  1728.  
  1729.   return REG_NOERROR;
  1730. } /* regex_compile */
  1731.  
  1732. /* Subroutines for `regex_compile'.  */
  1733.  
  1734. /* Store OP at LOC followed by two-byte integer parameter ARG.  */
  1735.  
  1736. static void
  1737. store_op1 (op, loc, arg)
  1738.     re_opcode_t op;
  1739.     unsigned char *loc;
  1740.     int arg;
  1741. {
  1742.   *loc = (unsigned char) op;
  1743.   STORE_NUMBER (loc + 1, arg);
  1744. }
  1745.  
  1746.  
  1747. /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
  1748.  
  1749. static void
  1750. store_op2 (op, loc, arg1, arg2)
  1751.     re_opcode_t op;
  1752.     unsigned char *loc;
  1753.     int arg1, arg2;
  1754. {
  1755.   *loc = (unsigned char) op;
  1756.   STORE_NUMBER (loc + 1, arg1);
  1757.   STORE_NUMBER (loc + 3, arg2);
  1758. }
  1759.  
  1760.  
  1761. /* Copy the bytes from LOC to END to open up three bytes of space at LOC
  1762.    for OP followed by two-byte integer parameter ARG.  */
  1763.  
  1764. static void
  1765. insert_op1 (op, loc, arg, end)
  1766.     re_opcode_t op;
  1767.     unsigned char *loc;
  1768.     int arg;
  1769.     unsigned char *end;    
  1770. {
  1771.   register unsigned char *pfrom = end;
  1772.   register unsigned char *pto = end + 3;
  1773.  
  1774.   while (pfrom != loc)
  1775.     *--pto = *--pfrom;
  1776.     
  1777.   store_op1 (op, loc, arg);
  1778. }
  1779.  
  1780.  
  1781. /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
  1782.  
  1783. static void
  1784. insert_op2 (op, loc, arg1, arg2, end)
  1785.     re_opcode_t op;
  1786.     unsigned char *loc;
  1787.     int arg1, arg2;
  1788.     unsigned char *end;    
  1789. {
  1790.   register unsigned char *pfrom = end;
  1791.   register unsigned char *pto = end + 5;
  1792.  
  1793.   while (pfrom != loc)
  1794.     *--pto = *--pfrom;
  1795.     
  1796.   store_op2 (op, loc, arg1, arg2);
  1797. }
  1798.  
  1799.  
  1800. /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
  1801.    after an alternative or a begin-subexpression.  We assume there is at
  1802.    least one character before the ^.  */
  1803.  
  1804. static boolean
  1805. at_begline_loc_p (pattern, p, syntax)
  1806.     const char *pattern, *p;
  1807.     reg_syntax_t syntax;
  1808. {
  1809.   const char *prev = p - 2;
  1810.   boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
  1811.   
  1812.   return
  1813.        /* After a subexpression?  */
  1814.        (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
  1815.        /* After an alternative?  */
  1816.     || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
  1817. }
  1818.  
  1819.  
  1820. /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
  1821.    at least one character after the $, i.e., `P < PEND'.  */
  1822.  
  1823. static boolean
  1824. at_endline_loc_p (p, pend, syntax)
  1825.     const char *p, *pend;
  1826.     int syntax;
  1827. {
  1828.   const char *next = p;
  1829.   boolean next_backslash = *next == '\\';
  1830.   const char *next_next = p + 1 < pend ? p + 1 : NULL;
  1831.   
  1832.   return
  1833.        /* Before a subexpression?  */
  1834.        (syntax & RE_NO_BK_PARENS ? *next == ')'
  1835.         : next_backslash && next_next && *next_next == ')')
  1836.        /* Before an alternative?  */
  1837.     || (syntax & RE_NO_BK_VBAR ? *next == '|'
  1838.         : next_backslash && next_next && *next_next == '|');
  1839. }
  1840.  
  1841.  
  1842. /* Returns true if REGNUM is in one of COMPILE_STACK's elements and 
  1843.    false if it's not.  */
  1844.  
  1845. static boolean
  1846. group_in_compile_stack (compile_stack, regnum)
  1847.     compile_stack_type compile_stack;
  1848.     regnum_t regnum;
  1849. {
  1850.   int this_element;
  1851.  
  1852.   for (this_element = compile_stack.avail - 1;  
  1853.        this_element >= 0; 
  1854.        this_element--)
  1855.     if (compile_stack.stack[this_element].regnum == regnum)
  1856.       return true;
  1857.  
  1858.   return false;
  1859. }
  1860.  
  1861.  
  1862. /* Read the ending character of a range (in a bracket expression) from the
  1863.    uncompiled pattern *P_PTR (which ends at PEND).  We assume the
  1864.    starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
  1865.    Then we set the translation of all bits between the starting and
  1866.    ending characters (inclusive) in the compiled pattern B.
  1867.    
  1868.    Return an error code.
  1869.    
  1870.    We use these short variable names so we can use the same macros as
  1871.    `regex_compile' itself.  */
  1872.  
  1873. static reg_errcode_t
  1874. compile_range (p_ptr, pend, translate, syntax, b)
  1875.     const char **p_ptr, *pend;
  1876.     char *translate;
  1877.     reg_syntax_t syntax;
  1878.     unsigned char *b;
  1879. {
  1880.   unsigned this_char;
  1881.  
  1882.   const char *p = *p_ptr;
  1883.   int range_start, range_end;
  1884.   
  1885.   if (p == pend)
  1886.     return REG_ERANGE;
  1887.  
  1888.   /* Even though the pattern is a signed `char *', we need to fetch
  1889.      with unsigned char *'s; if the high bit of the pattern character
  1890.      is set, the range endpoints will be negative if we fetch using a
  1891.      signed char *.
  1892.  
  1893.      We also want to fetch the endpoints without translating them; the 
  1894.      appropriate translation is done in the bit-setting loop below.  */
  1895.   range_start = ((unsigned char *) p)[-2];
  1896.   range_end   = ((unsigned char *) p)[0];
  1897.  
  1898.   /* Have to increment the pointer into the pattern string, so the
  1899.      caller isn't still at the ending character.  */
  1900.   (*p_ptr)++;
  1901.  
  1902.   /* If the start is after the end, the range is empty.  */
  1903.   if (range_start > range_end)
  1904.     return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
  1905.  
  1906.   /* Here we see why `this_char' has to be larger than an `unsigned
  1907.      char' -- the range is inclusive, so if `range_end' == 0xff
  1908.      (assuming 8-bit characters), we would otherwise go into an infinite
  1909.      loop, since all characters <= 0xff.  */
  1910.   for (this_char = range_start; this_char <= range_end; this_char++)
  1911.     {
  1912.       SET_LIST_BIT (TRANSLATE (this_char));
  1913.     }
  1914.   
  1915.   return REG_NOERROR;
  1916. }
  1917.  
  1918. /* Failure stack declarations and macros; both re_compile_fastmap and
  1919.    re_match_2 use a failure stack.  These have to be macros because of
  1920.    REGEX_ALLOCATE.  */
  1921.    
  1922.  
  1923. /* Number of failure points for which to initially allocate space
  1924.    when matching.  If this number is exceeded, we allocate more
  1925.    space, so it is not a hard limit.  */
  1926. #ifndef INIT_FAILURE_ALLOC
  1927. #define INIT_FAILURE_ALLOC 5
  1928. #endif
  1929.  
  1930. /* Roughly the maximum number of failure points on the stack.  Would be
  1931.    exactly that if always used MAX_FAILURE_SPACE each time we failed.
  1932.    This is a variable only so users of regex can assign to it; we never
  1933.    change it ourselves.  */
  1934. int re_max_failures = 2000;
  1935.  
  1936. typedef const unsigned char *fail_stack_elt_t;
  1937.  
  1938. typedef struct
  1939. {
  1940.   fail_stack_elt_t *stack;
  1941.   unsigned size;
  1942.   unsigned avail;            /* Offset of next open position.  */
  1943. } fail_stack_type;
  1944.  
  1945. #define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
  1946. #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
  1947. #define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
  1948. #define FAIL_STACK_TOP()       (fail_stack.stack[fail_stack.avail])
  1949.  
  1950.  
  1951. /* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
  1952.  
  1953. #define INIT_FAIL_STACK()                        \
  1954.   do {                                    \
  1955.     fail_stack.stack = (fail_stack_elt_t *)                \
  1956.       REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));    \
  1957.                                     \
  1958.     if (fail_stack.stack == NULL)                    \
  1959.       return -2;                            \
  1960.                                     \
  1961.     fail_stack.size = INIT_FAILURE_ALLOC;                \
  1962.     fail_stack.avail = 0;                        \
  1963.   } while(0);
  1964.  
  1965.  
  1966. /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
  1967.  
  1968.    Return 1 if succeeds, and 0 if either ran out of memory
  1969.    allocating space for it or it was already too large.  
  1970.    
  1971.    REGEX_REALLOCATE requires `destination' be declared.   */
  1972.  
  1973. #define DOUBLE_FAIL_STACK(fail_stack)                    \
  1974.   ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS        \
  1975.    ? 0                                    \
  1976.    : ((fail_stack).stack = (fail_stack_elt_t *)                \
  1977.         REGEX_REALLOCATE ((fail_stack).stack,                 \
  1978.           (fail_stack).size * sizeof (fail_stack_elt_t),        \
  1979.           ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),    \
  1980.                                     \
  1981.       (fail_stack).stack == NULL                    \
  1982.       ? 0                                \
  1983.       : ((fail_stack).size <<= 1,                     \
  1984.          1)))
  1985.  
  1986.  
  1987. /* Push PATTERN_OP on FAIL_STACK. 
  1988.  
  1989.    Return 1 if was able to do so and 0 if ran out of memory allocating
  1990.    space to do so.  */
  1991. #define PUSH_PATTERN_OP(pattern_op, fail_stack)                \
  1992.   ((FAIL_STACK_FULL ()                            \
  1993.     && !DOUBLE_FAIL_STACK (fail_stack))                    \
  1994.     ? 0                                    \
  1995.     : ((fail_stack).stack[(fail_stack).avail++] = pattern_op,        \
  1996.        1))
  1997.  
  1998. /* This pushes an item onto the failure stack.  Must be a four-byte
  1999.    value.  Assumes the variable `fail_stack'.  Probably should only
  2000.    be called from within `PUSH_FAILURE_POINT'.  */
  2001. #define PUSH_FAILURE_ITEM(item)                        \
  2002.   fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
  2003.  
  2004. /* The complement operation.  Assumes `fail_stack' is nonempty.  */
  2005. #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
  2006.  
  2007. /* Used to omit pushing failure point id's when we're not debugging.  */
  2008.  
  2009.  
  2010. /* Push the information about the state we will need
  2011.    if we ever fail back to it.  
  2012.    
  2013.    Requires variables fail_stack, regstart, regend, reg_info, and
  2014.    num_regs be declared.  DOUBLE_FAIL_STACK requires `destination' be
  2015.    declared.
  2016.    
  2017.    Does `return FAILURE_CODE' if runs out of memory.  */
  2018.  
  2019. #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)    \
  2020.   do {                                    \
  2021.     char *destination;                            \
  2022.     /* Must be int, so when we don't save any registers, the arithmetic    \
  2023.        of 0 + -1 isn't done as unsigned.  */                \
  2024.     int this_reg;                            \
  2025.                                         \
  2026.                                     \
  2027.     /* Ensure we have enough space allocated for what we will push.  */    \
  2028.     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)            \
  2029.       {                                    \
  2030.         if (!DOUBLE_FAIL_STACK (fail_stack))            \
  2031.           return failure_code;                        \
  2032.                                     \
  2033.       }                                    \
  2034.                                     \
  2035.     /* Push the info, starting with the registers.  */            \
  2036.                                     \
  2037.     for (this_reg = lowest_active_reg; this_reg <= highest_active_reg;    \
  2038.          this_reg++)                            \
  2039.       {                                    \
  2040.                                     \
  2041.         PUSH_FAILURE_ITEM (regstart[this_reg]);                \
  2042.                                                                         \
  2043.         PUSH_FAILURE_ITEM (regend[this_reg]);                \
  2044.                                     \
  2045.         PUSH_FAILURE_ITEM (reg_info[this_reg].word);            \
  2046.       }                                    \
  2047.                                     \
  2048.     PUSH_FAILURE_ITEM (lowest_active_reg);                \
  2049.                                     \
  2050.     PUSH_FAILURE_ITEM (highest_active_reg);                \
  2051.                                     \
  2052.     PUSH_FAILURE_ITEM (pattern_place);                    \
  2053.                                     \
  2054.     PUSH_FAILURE_ITEM (string_place);                    \
  2055.                                     \
  2056.   } while(0);
  2057.  
  2058. /* This is the number of items that are pushed and popped on the stack
  2059.    for each register.  */
  2060. #define NUM_REG_ITEMS  3
  2061.  
  2062. /* Individual items aside from the registers.  */
  2063. #ifdef DEBUG
  2064. #define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
  2065. #else
  2066. #define NUM_NONREG_ITEMS 4
  2067. #endif
  2068.  
  2069. /* We push at most this many items on the stack.  */
  2070. #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
  2071.  
  2072. /* We actually push this many items.  */
  2073. #define NUM_FAILURE_ITEMS                        \
  2074.   ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS     \
  2075.     + NUM_NONREG_ITEMS)
  2076.  
  2077. /* How many items can still be added to the stack without overflowing it.  */
  2078. #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
  2079.  
  2080.  
  2081. /* Pops what PUSH_FAIL_STACK pushes.
  2082.  
  2083.    We restore into the parameters, all of which should be lvalues:
  2084.      STR -- the saved data position.
  2085.      PAT -- the saved pattern position.
  2086.      LOW_REG, HIGH_REG -- the highest and lowest active registers.
  2087.      REGSTART, REGEND -- arrays of string positions.
  2088.      REG_INFO -- array of information about each subexpression.
  2089.    
  2090.    Also assumes the variables `fail_stack' and (if debugging), `bufp',
  2091.    `pend', `string1', `size1', `string2', and `size2'.  */
  2092.  
  2093. #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
  2094. {                                    \
  2095.   int this_reg;                                \
  2096.   const unsigned char *string_temp;                    \
  2097.                                     \
  2098. /*  assert (!FAIL_STACK_EMPTY ());*/                    \
  2099.                                     \
  2100.   /* Remove failure points and point to how many regs pushed.  */    \
  2101.                                     \
  2102. /*  assert (fail_stack.avail >= NUM_NONREG_ITEMS);*/            \
  2103.                                     \
  2104.                                     \
  2105.   /* If the saved string location is NULL, it came from an        \
  2106.      on_failure_keep_string_jump opcode, and we want to throw away the    \
  2107.      saved NULL, thus retaining our current position in the string.  */    \
  2108.   string_temp = POP_FAILURE_ITEM ();                    \
  2109.   if (string_temp != NULL)                        \
  2110.     str = (const char *) string_temp;                    \
  2111.                                     \
  2112.                                     \
  2113.   pat = (unsigned char *) POP_FAILURE_ITEM ();                \
  2114.                                     \
  2115.   /* Restore register info.  */                        \
  2116.   high_reg = (unsigned) POP_FAILURE_ITEM ();                \
  2117.                                     \
  2118.   low_reg = (unsigned) POP_FAILURE_ITEM ();                \
  2119.                                     \
  2120.   for (this_reg = high_reg; this_reg >= low_reg; this_reg--)        \
  2121.     {                                    \
  2122.                                     \
  2123.       reg_info[this_reg].word = POP_FAILURE_ITEM ();            \
  2124.                                     \
  2125.       regend[this_reg] = (const char *) POP_FAILURE_ITEM ();        \
  2126.                                     \
  2127.       regstart[this_reg] = (const char *) POP_FAILURE_ITEM ();        \
  2128.     }                                    \
  2129.                                     \
  2130. } /* POP_FAILURE_POINT */
  2131.  
  2132. /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
  2133.    BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
  2134.    characters can start a string that matches the pattern.  This fastmap
  2135.    is used by re_search to skip quickly over impossible starting points.
  2136.  
  2137.    The caller must supply the address of a (1 << BYTEWIDTH)-byte data
  2138.    area as BUFP->fastmap.
  2139.    
  2140.    We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
  2141.    the pattern buffer.
  2142.  
  2143.    Returns 0 if we succeed, -2 if an internal error.   */
  2144.  
  2145. int
  2146. re_compile_fastmap (bufp)
  2147.      struct re_pattern_buffer *bufp;
  2148. {
  2149.   int j, k;
  2150.   fail_stack_type fail_stack;
  2151. #ifndef REGEX_MALLOC
  2152.   char *destination;
  2153. #endif
  2154.   /* We don't push any register information onto the failure stack.  */
  2155.   unsigned num_regs = 0;
  2156.   
  2157.   register char *fastmap = bufp->fastmap;
  2158.   unsigned char *pattern = bufp->buffer;
  2159.   unsigned long size = bufp->used;
  2160.   const unsigned char *p = pattern;
  2161.   register unsigned char *pend = pattern + size;
  2162.  
  2163.   /* Assume that each path through the pattern can be null until
  2164.      proven otherwise.  We set this false at the bottom of switch
  2165.      statement, to which we get only if a particular path doesn't
  2166.      match the empty string.  */
  2167.   boolean path_can_be_null = true;
  2168.  
  2169.   /* We aren't doing a `succeed_n' to begin with.  */
  2170.   boolean succeed_n_p = false;
  2171.  
  2172. /*  assert (fastmap != NULL && p != NULL);*/
  2173.   
  2174.   INIT_FAIL_STACK ();
  2175.   bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
  2176.   bufp->fastmap_accurate = 1;        /* It will be when we're done.  */
  2177.   bufp->can_be_null = 0;
  2178.       
  2179.   while (p != pend || !FAIL_STACK_EMPTY ())
  2180.     {
  2181.       if (p == pend)
  2182.         {
  2183.           bufp->can_be_null |= path_can_be_null;
  2184.           
  2185.           /* Reset for next path.  */
  2186.           path_can_be_null = true;
  2187.           
  2188.           p = fail_stack.stack[--fail_stack.avail];
  2189.     }
  2190.  
  2191.       /* We should never be about to go beyond the end of the pattern.  */
  2192. /*      assert (p < pend);*/
  2193.       
  2194. #ifdef SWITCH_ENUM_BUG
  2195.       switch ((int) ((re_opcode_t) *p++))
  2196. #else
  2197.       switch ((re_opcode_t) *p++)
  2198. #endif
  2199.     {
  2200.  
  2201.         /* I guess the idea here is to simply not bother with a fastmap
  2202.            if a backreference is used, since it's too hard to figure out
  2203.            the fastmap for the corresponding group.  Setting
  2204.            `can_be_null' stops `re_search_2' from using the fastmap, so
  2205.            that is all we do.  */
  2206.     case duplicate:
  2207.       bufp->can_be_null = 1;
  2208.           return 0;
  2209.  
  2210.  
  2211.       /* Following are the cases which match a character.  These end
  2212.          with `break'.  */
  2213.  
  2214.     case exactn:
  2215.           fastmap[p[1]] = 1;
  2216.       break;
  2217.  
  2218.  
  2219.         case charset:
  2220.           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  2221.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  2222.               fastmap[j] = 1;
  2223.       break;
  2224.  
  2225.  
  2226.     case charset_not:
  2227.       /* Chars beyond end of map must be allowed.  */
  2228.       for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  2229.             fastmap[j] = 1;
  2230.  
  2231.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  2232.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  2233.               fastmap[j] = 1;
  2234.           break;
  2235.  
  2236.  
  2237.     case wordchar:
  2238.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2239.         if (SYNTAX (j) == Sword)
  2240.           fastmap[j] = 1;
  2241.       break;
  2242.  
  2243.  
  2244.     case notwordchar:
  2245.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2246.         if (SYNTAX (j) != Sword)
  2247.           fastmap[j] = 1;
  2248.       break;
  2249.  
  2250.  
  2251.         case anychar:
  2252.           /* `.' matches anything ...  */
  2253.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2254.             fastmap[j] = 1;
  2255.  
  2256.           /* ... except perhaps newline.  */
  2257.           if (!(bufp->syntax & RE_DOT_NEWLINE))
  2258.             fastmap['\n'] = 0;
  2259.  
  2260.           /* Return if we have already set `can_be_null'; if we have,
  2261.              then the fastmap is irrelevant.  Something's wrong here.  */
  2262.       else if (bufp->can_be_null)
  2263.         return 0;
  2264.  
  2265.           /* Otherwise, have to check alternative paths.  */
  2266.       break;
  2267.  
  2268.  
  2269. #ifdef emacs
  2270.         case syntaxspec:
  2271.       k = *p++;
  2272.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2273.         if (SYNTAX (j) == (enum syntaxcode) k)
  2274.           fastmap[j] = 1;
  2275.       break;
  2276.  
  2277.  
  2278.     case notsyntaxspec:
  2279.       k = *p++;
  2280.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2281.         if (SYNTAX (j) != (enum syntaxcode) k)
  2282.           fastmap[j] = 1;
  2283.       break;
  2284.  
  2285.  
  2286.       /* All cases after this match the empty string.  These end with
  2287.          `continue'.  */
  2288.  
  2289.  
  2290.     case before_dot:
  2291.     case at_dot:
  2292.     case after_dot:
  2293.           continue;
  2294. #endif /* not emacs */
  2295.  
  2296.  
  2297.         case no_op:
  2298.         case begline:
  2299.         case endline:
  2300.     case begbuf:
  2301.     case endbuf:
  2302.     case wordbound:
  2303.     case notwordbound:
  2304.     case wordbeg:
  2305.     case wordend:
  2306.         case push_dummy_failure:
  2307.           continue;
  2308.  
  2309.  
  2310.     case jump_n:
  2311.         case pop_failure_jump:
  2312.     case maybe_pop_jump:
  2313.     case jump:
  2314.         case jump_past_alt:
  2315.     case dummy_failure_jump:
  2316.           EXTRACT_NUMBER_AND_INCR (j, p);
  2317.       p += j;    
  2318.       if (j > 0)
  2319.         continue;
  2320.             
  2321.           /* Jump backward implies we just went through the body of a
  2322.              loop and matched nothing.  Opcode jumped to should be
  2323.              `on_failure_jump' or `succeed_n'.  Just treat it like an
  2324.              ordinary jump.  For a * loop, it has pushed its failure
  2325.              point already; if so, discard that as redundant.  */
  2326.           if ((re_opcode_t) *p != on_failure_jump
  2327.           && (re_opcode_t) *p != succeed_n)
  2328.         continue;
  2329.  
  2330.           p++;
  2331.           EXTRACT_NUMBER_AND_INCR (j, p);
  2332.           p += j;        
  2333.       
  2334.           /* If what's on the stack is where we are now, pop it.  */
  2335.           if (!FAIL_STACK_EMPTY () 
  2336.           && fail_stack.stack[fail_stack.avail - 1] == p)
  2337.             fail_stack.avail--;
  2338.  
  2339.           continue;
  2340.  
  2341.  
  2342.         case on_failure_jump:
  2343.         case on_failure_keep_string_jump:
  2344.     handle_on_failure_jump:
  2345.           EXTRACT_NUMBER_AND_INCR (j, p);
  2346.  
  2347.           /* For some patterns, e.g., `(a?)?', `p+j' here points to the
  2348.              end of the pattern.  We don't want to push such a point,
  2349.              since when we restore it above, entering the switch will
  2350.              increment `p' past the end of the pattern.  We don't need
  2351.              to push such a point since we obviously won't find any more
  2352.              fastmap entries beyond `pend'.  Such a pattern can match
  2353.              the null string, though.  */
  2354.           if (p + j < pend)
  2355.             {
  2356.               if (!PUSH_PATTERN_OP (p + j, fail_stack))
  2357.                 return -2;
  2358.             }
  2359.           else
  2360.             bufp->can_be_null = 1;
  2361.  
  2362.           if (succeed_n_p)
  2363.             {
  2364.               EXTRACT_NUMBER_AND_INCR (k, p);    /* Skip the n.  */
  2365.               succeed_n_p = false;
  2366.         }
  2367.  
  2368.           continue;
  2369.  
  2370.  
  2371.     case succeed_n:
  2372.           /* Get to the number of times to succeed.  */
  2373.           p += 2;        
  2374.  
  2375.           /* Increment p past the n for when k != 0.  */
  2376.           EXTRACT_NUMBER_AND_INCR (k, p);
  2377.           if (k == 0)
  2378.         {
  2379.               p -= 4;
  2380.             succeed_n_p = true;  /* Spaghetti code alert.  */
  2381.               goto handle_on_failure_jump;
  2382.             }
  2383.           continue;
  2384.  
  2385.  
  2386.     case set_number_at:
  2387.           p += 4;
  2388.           continue;
  2389.  
  2390.  
  2391.     case start_memory:
  2392.         case stop_memory:
  2393.       p += 2;
  2394.       continue;
  2395.  
  2396.  
  2397.     default:
  2398.           abort (); /* We have listed all the cases.  */
  2399.         } /* switch *p++ */
  2400.  
  2401.       /* Getting here means we have found the possible starting
  2402.          characters for one path of the pattern -- and that the empty
  2403.          string does not match.  We need not follow this path further.
  2404.          Instead, look at the next alternative (remembered on the
  2405.          stack), or quit if no more.  The test at the top of the loop
  2406.          does these things.  */
  2407.       path_can_be_null = false;
  2408.       p = pend;
  2409.     } /* while p */
  2410.  
  2411.   /* Set `can_be_null' for the last path (also the first path, if the
  2412.      pattern is empty).  */
  2413.   bufp->can_be_null |= path_can_be_null;
  2414.   return 0;
  2415. } /* re_compile_fastmap */
  2416.  
  2417. /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
  2418.    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
  2419.    this memory for recording register information.  STARTS and ENDS
  2420.    must be allocated using the malloc library routine, and must each
  2421.    be at least NUM_REGS * sizeof (regoff_t) bytes long.
  2422.  
  2423.    If NUM_REGS == 0, then subsequent matches should allocate their own
  2424.    register data.
  2425.  
  2426.    Unless this function is called, the first search or match using
  2427.    PATTERN_BUFFER will allocate its own register data, without
  2428.    freeing the old data.  */
  2429.  
  2430. void
  2431. re_set_registers (bufp, regs, num_regs, starts, ends)
  2432.     struct re_pattern_buffer *bufp;
  2433.     struct re_registers *regs;
  2434.     unsigned num_regs;
  2435.     regoff_t *starts, *ends;
  2436. {
  2437.   if (num_regs)
  2438.     {
  2439.       bufp->regs_allocated = REGS_REALLOCATE;
  2440.       regs->num_regs = num_regs;
  2441.       regs->start = starts;
  2442.       regs->end = ends;
  2443.     }
  2444.   else
  2445.     {
  2446.       bufp->regs_allocated = REGS_UNALLOCATED;
  2447.       regs->num_regs = 0;
  2448.       regs->start = regs->end = (regoff_t) 0;
  2449.     }
  2450. }
  2451.  
  2452. /* Searching routines.  */
  2453.  
  2454. /* Like re_search_2, below, but only one string is specified, and
  2455.    doesn't let you say where to stop matching. */
  2456.  
  2457. int
  2458. re_search (bufp, string, size, startpos, range, regs)
  2459.      struct re_pattern_buffer *bufp;
  2460.      const char *string;
  2461.      int size, startpos, range;
  2462.      struct re_registers *regs;
  2463. {
  2464.   return re_search_2 (bufp, NULL, 0, string, size, startpos, range, 
  2465.               regs, size);
  2466. }
  2467.  
  2468.  
  2469. /* Using the compiled pattern in BUFP->buffer, first tries to match the
  2470.    virtual concatenation of STRING1 and STRING2, starting first at index
  2471.    STARTPOS, then at STARTPOS + 1, and so on.
  2472.    
  2473.    STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
  2474.    
  2475.    RANGE is how far to scan while trying to match.  RANGE = 0 means try
  2476.    only at STARTPOS; in general, the last start tried is STARTPOS +
  2477.    RANGE.
  2478.    
  2479.    In REGS, return the indices of the virtual concatenation of STRING1
  2480.    and STRING2 that matched the entire BUFP->buffer and its contained
  2481.    subexpressions.
  2482.    
  2483.    Do not consider matching one past the index STOP in the virtual
  2484.    concatenation of STRING1 and STRING2.
  2485.  
  2486.    We return either the position in the strings at which the match was
  2487.    found, -1 if no match, or -2 if error (such as failure
  2488.    stack overflow).  */
  2489.  
  2490. int
  2491. re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
  2492.      struct re_pattern_buffer *bufp;
  2493.      const char *string1, *string2;
  2494.      int size1, size2;
  2495.      int startpos;
  2496.      int range;
  2497.      struct re_registers *regs;
  2498.      int stop;
  2499. {
  2500.   int val;
  2501.   register char *fastmap = bufp->fastmap;
  2502.   register char *translate = bufp->translate;
  2503.   int total_size = size1 + size2;
  2504.   int endpos = startpos + range;
  2505.  
  2506.   /* Check for out-of-range STARTPOS.  */
  2507.   if (startpos < 0 || startpos > total_size)
  2508.     return -1;
  2509.     
  2510.   /* Fix up RANGE if it might eventually take us outside
  2511.      the virtual concatenation of STRING1 and STRING2.  */
  2512.   if (endpos < -1)
  2513.     range = -1 - startpos;
  2514.   else if (endpos > total_size)
  2515.     range = total_size - startpos;
  2516.  
  2517.   /* If the search isn't to be a backwards one, don't waste time in a
  2518.      search for a pattern that must be anchored.  */
  2519.   if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
  2520.     {
  2521.       if (startpos > 0)
  2522.     return -1;
  2523.       else
  2524.     range = 1;
  2525.     }
  2526.  
  2527.   /* Update the fastmap now if not correct already.  */
  2528.   if (fastmap && !bufp->fastmap_accurate)
  2529.     if (re_compile_fastmap (bufp) == -2)
  2530.       return -2;
  2531.   
  2532.   /* Loop through the string, looking for a place to start matching.  */
  2533.   for (;;)
  2534.     { 
  2535.       /* If a fastmap is supplied, skip quickly over characters that
  2536.          cannot be the start of a match.  If the pattern can match the
  2537.          null string, however, we don't need to skip characters; we want
  2538.          the first null string.  */
  2539.       if (fastmap && startpos < total_size && !bufp->can_be_null)
  2540.     {
  2541.       if (range > 0)    /* Searching forwards.  */
  2542.         {
  2543.           register const char *d;
  2544.           register int lim = 0;
  2545.           int irange = range;
  2546.  
  2547.               if (startpos < size1 && startpos + range >= size1)
  2548.                 lim = range - (size1 - startpos);
  2549.  
  2550.           d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
  2551.    
  2552.               /* Written out as an if-else to avoid testing `translate'
  2553.                  inside the loop.  */
  2554.           if (translate)
  2555.                 while (range > lim
  2556.                        && !fastmap[(unsigned char)
  2557.                    translate[(unsigned char) *d++]])
  2558.                   range--;
  2559.           else
  2560.                 while (range > lim && !fastmap[(unsigned char) *d++])
  2561.                   range--;
  2562.  
  2563.           startpos += irange - range;
  2564.         }
  2565.       else                /* Searching backwards.  */
  2566.         {
  2567.           register char c = (size1 == 0 || startpos >= size1
  2568.                                  ? string2[startpos - size1] 
  2569.                                  : string1[startpos]);
  2570.  
  2571.           if (!fastmap[(unsigned char) TRANSLATE (c)])
  2572.         goto advance;
  2573.         }
  2574.     }
  2575.  
  2576.       /* If can't match the null string, and that's all we have left, fail.  */
  2577.       if (range >= 0 && startpos == total_size && fastmap
  2578.           && !bufp->can_be_null)
  2579.     return -1;
  2580.  
  2581.       val = re_match_2 (bufp, string1, size1, string2, size2,
  2582.                     startpos, regs, stop);
  2583.       if (val >= 0)
  2584.     return startpos;
  2585.         
  2586.       if (val == -2)
  2587.     return -2;
  2588.  
  2589.     advance:
  2590.       if (!range) 
  2591.         break;
  2592.       else if (range > 0) 
  2593.         {
  2594.           range--; 
  2595.           startpos++;
  2596.         }
  2597.       else
  2598.         {
  2599.           range++; 
  2600.           startpos--;
  2601.         }
  2602.     }
  2603.   return -1;
  2604. } /* re_search_2 */
  2605.  
  2606. /* Declarations and macros for re_match_2.  */
  2607.  
  2608. static int bcmp_translate ();
  2609. static boolean alt_match_null_string_p (),
  2610.                common_op_match_null_string_p (),
  2611.                group_match_null_string_p ();
  2612.  
  2613. /* Structure for per-register (a.k.a. per-group) information.
  2614.    This must not be longer than one word, because we push this value
  2615.    onto the failure stack.  Other register information, such as the
  2616.    starting and ending positions (which are addresses), and the list of
  2617.    inner groups (which is a bits list) are maintained in separate
  2618.    variables.  
  2619.    
  2620.    We are making a (strictly speaking) nonportable assumption here: that
  2621.    the compiler will pack our bit fields into something that fits into
  2622.    the type of `word', i.e., is something that fits into one item on the
  2623.    failure stack.  */
  2624. typedef union
  2625. {
  2626.   fail_stack_elt_t word;
  2627.   struct
  2628.   {
  2629.       /* This field is one if this group can match the empty string,
  2630.          zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
  2631. #define MATCH_NULL_UNSET_VALUE 3
  2632.     unsigned match_null_string_p : 2;
  2633.     unsigned is_active : 1;
  2634.     unsigned matched_something : 1;
  2635.     unsigned ever_matched_something : 1;
  2636.   } bits;
  2637. } register_info_type;
  2638.  
  2639. #define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
  2640. #define IS_ACTIVE(R)  ((R).bits.is_active)
  2641. #define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
  2642. #define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
  2643.  
  2644.  
  2645. /* Call this when have matched a real character; it sets `matched' flags
  2646.    for the subexpressions which we are currently inside.  Also records
  2647.    that those subexprs have matched.  */
  2648. #define SET_REGS_MATCHED()                        \
  2649.   do                                    \
  2650.     {                                    \
  2651.       unsigned r;                            \
  2652.       for (r = lowest_active_reg; r <= highest_active_reg; r++)        \
  2653.         {                                \
  2654.           MATCHED_SOMETHING (reg_info[r])                \
  2655.             = EVER_MATCHED_SOMETHING (reg_info[r])            \
  2656.             = 1;                            \
  2657.         }                                \
  2658.     }                                    \
  2659.   while(0);
  2660.  
  2661.  
  2662. /* This converts PTR, a pointer into one of the search strings `string1'
  2663.    and `string2' into an offset from the beginning of that string.  */
  2664. #define POINTER_TO_OFFSET(ptr)                        \
  2665.   (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
  2666.  
  2667. /* Registers are set to a sentinel when they haven't yet matched.  */
  2668. #define REG_UNSET_VALUE ((char *) -1)
  2669. #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
  2670.  
  2671.  
  2672. /* Macros for dealing with the split strings in re_match_2.  */
  2673.  
  2674. #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
  2675.  
  2676. /* Call before fetching a character with *d.  This switches over to
  2677.    string2 if necessary.  */
  2678. #define PREFETCH()                            \
  2679.   while (d == dend)                                \
  2680.     {                                    \
  2681.       /* End of string2 => fail.  */                    \
  2682.       if (dend == end_match_2)                         \
  2683.         goto fail;                            \
  2684.       /* End of string1 => advance to string2.  */             \
  2685.       d = string2;                                \
  2686.       dend = end_match_2;                        \
  2687.     }
  2688.  
  2689.  
  2690. /* Test if at very beginning or at very end of the virtual concatenation
  2691.    of `string1' and `string2'.  If only one string, it's `string2'.  */
  2692. #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
  2693. #define AT_STRINGS_END(d) ((d) == end2)    
  2694.  
  2695.  
  2696. /* Test if D points to a character which is word-constituent.  We have
  2697.    two special cases to check for: if past the end of string1, look at
  2698.    the first character in string2; and if before the beginning of
  2699.    string2, look at the last character in string1.  */
  2700. #define WORDCHAR_P(d)                            \
  2701.   (SYNTAX ((d) == end1 ? *string2                    \
  2702.            : (d) == string2 - 1 ? *(end1 - 1) : *(d))            \
  2703.    == Sword)
  2704.  
  2705. /* Test if the character before D and the one at D differ with respect
  2706.    to being word-constituent.  */
  2707. #define AT_WORD_BOUNDARY(d)                        \
  2708.   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                \
  2709.    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
  2710.  
  2711.  
  2712. /* Free everything we malloc.  */
  2713. #ifdef REGEX_MALLOC
  2714. #define FREE_VAR(var) if (var) free (var); var = NULL
  2715. #define FREE_VARIABLES()                        \
  2716.   do {                                    \
  2717.     FREE_VAR (fail_stack.stack);                    \
  2718.     FREE_VAR (regstart);                        \
  2719.     FREE_VAR (regend);                            \
  2720.     FREE_VAR (old_regstart);                        \
  2721.     FREE_VAR (old_regend);                        \
  2722.     FREE_VAR (best_regstart);                        \
  2723.     FREE_VAR (best_regend);                        \
  2724.     FREE_VAR (reg_info);                        \
  2725.     FREE_VAR (reg_dummy);                        \
  2726.     FREE_VAR (reg_info_dummy);                        \
  2727.   } while(0);
  2728. #else /* not REGEX_MALLOC */
  2729. /* Some MIPS systems (at least) want this to free alloca'd storage.  */
  2730. #define FREE_VARIABLES() alloca (0)
  2731. #endif /* not REGEX_MALLOC */
  2732.  
  2733.  
  2734. /* These values must meet several constraints.  They must not be valid
  2735.    register values; since we have a limit of 255 registers (because
  2736.    we use only one byte in the pattern for the register number), we can
  2737.    use numbers larger than 255.  They must differ by 1, because of
  2738.    NUM_FAILURE_ITEMS above.  And the value for the lowest register must
  2739.    be larger than the value for the highest register, so we do not try
  2740.    to actually save any registers when none are active.  */
  2741. #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
  2742. #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
  2743.  
  2744. /* Matching routines.  */
  2745.  
  2746. #ifndef emacs   /* Emacs never uses this.  */
  2747. /* re_match is like re_match_2 except it takes only a single string.  */
  2748.  
  2749. int
  2750. re_match (bufp, string, size, pos, regs)
  2751.      struct re_pattern_buffer *bufp;
  2752.      const char *string;
  2753.      int size, pos;
  2754.      struct re_registers *regs;
  2755.  {
  2756.   return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size); 
  2757. }
  2758. #endif /* not emacs */
  2759.  
  2760.  
  2761. /* re_match_2 matches the compiled pattern in BUFP against the
  2762.    the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
  2763.    and SIZE2, respectively).  We start matching at POS, and stop
  2764.    matching at STOP.
  2765.    
  2766.    If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
  2767.    store offsets for the substring each group matched in REGS.  See the
  2768.    documentation for exactly how many groups we fill.
  2769.  
  2770.    We return -1 if no match, -2 if an internal error (such as the
  2771.    failure stack overflowing).  Otherwise, we return the length of the
  2772.    matched substring.  */
  2773.  
  2774. int
  2775. re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
  2776.      struct re_pattern_buffer *bufp;
  2777.      const char *string1, *string2;
  2778.      int size1, size2;
  2779.      int pos;
  2780.      struct re_registers *regs;
  2781.      int stop;
  2782. {
  2783.   /* General temporaries.  */
  2784.   int mcnt;
  2785.   unsigned char *p1;
  2786.  
  2787.   /* Just past the end of the corresponding string.  */
  2788.   const char *end1, *end2;
  2789.  
  2790.   /* Pointers into string1 and string2, just past the last characters in
  2791.      each to consider matching.  */
  2792.   const char *end_match_1, *end_match_2;
  2793.  
  2794.   /* Where we are in the data, and the end of the current string.  */
  2795.   const char *d, *dend;
  2796.   
  2797.   /* Where we are in the pattern, and the end of the pattern.  */
  2798.   unsigned char *p = bufp->buffer;
  2799.   register unsigned char *pend = p + bufp->used;
  2800.  
  2801.   /* We use this to map every character in the string.  */
  2802.   char *translate = bufp->translate;
  2803.  
  2804.   /* Failure point stack.  Each place that can handle a failure further
  2805.      down the line pushes a failure point on this stack.  It consists of
  2806.      restart, regend, and reg_info for all registers corresponding to
  2807.      the subexpressions we're currently inside, plus the number of such
  2808.      registers, and, finally, two char *'s.  The first char * is where
  2809.      to resume scanning the pattern; the second one is where to resume
  2810.      scanning the strings.  If the latter is zero, the failure point is
  2811.      a ``dummy''; if a failure happens and the failure point is a dummy,
  2812.      it gets discarded and the next next one is tried.  */
  2813.   fail_stack_type fail_stack;
  2814.  
  2815.   /* We fill all the registers internally, independent of what we
  2816.      return, for use in backreferences.  The number here includes
  2817.      an element for register zero.  */
  2818.   unsigned num_regs = bufp->re_nsub + 1;
  2819.   
  2820.   /* The currently active registers.  */
  2821.   unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  2822.   unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  2823.  
  2824.   /* Information on the contents of registers. These are pointers into
  2825.      the input strings; they record just what was matched (on this
  2826.      attempt) by a subexpression part of the pattern, that is, the
  2827.      regnum-th regstart pointer points to where in the pattern we began
  2828.      matching and the regnum-th regend points to right after where we
  2829.      stopped matching the regnum-th subexpression.  (The zeroth register
  2830.      keeps track of what the whole pattern matches.)  */
  2831.   const char **regstart, **regend;
  2832.  
  2833.   /* If a group that's operated upon by a repetition operator fails to
  2834.      match anything, then the register for its start will need to be
  2835.      restored because it will have been set to wherever in the string we
  2836.      are when we last see its open-group operator.  Similarly for a
  2837.      register's end.  */
  2838.   const char **old_regstart, **old_regend;
  2839.  
  2840.   /* The is_active field of reg_info helps us keep track of which (possibly
  2841.      nested) subexpressions we are currently in. The matched_something
  2842.      field of reg_info[reg_num] helps us tell whether or not we have
  2843.      matched any of the pattern so far this time through the reg_num-th
  2844.      subexpression.  These two fields get reset each time through any
  2845.      loop their register is in.  */
  2846.   register_info_type *reg_info; 
  2847.  
  2848.   /* The following record the register info as found in the above
  2849.      variables when we find a match better than any we've seen before. 
  2850.      This happens as we backtrack through the failure points, which in
  2851.      turn happens only if we have not yet matched the entire string. */
  2852.   unsigned best_regs_set = false;
  2853.   const char **best_regstart, **best_regend;
  2854.   
  2855.   /* Logically, this is `best_regend[0]'.  But we don't want to have to
  2856.      allocate space for that if we're not allocating space for anything
  2857.      else (see below).  Also, we never need info about register 0 for
  2858.      any of the other register vectors, and it seems rather a kludge to
  2859.      treat `best_regend' differently than the rest.  So we keep track of
  2860.      the end of the best match so far in a separate variable.  We
  2861.      initialize this to NULL so that when we backtrack the first time
  2862.      and need to test it, it's not garbage.  */
  2863.   const char *match_end = NULL;
  2864.  
  2865.   /* Used when we pop values we don't care about.  */
  2866.   const char **reg_dummy;
  2867.   register_info_type *reg_info_dummy;
  2868.  
  2869.  
  2870.   
  2871.   INIT_FAIL_STACK ();
  2872.   
  2873.   /* Do not bother to initialize all the register variables if there are
  2874.      no groups in the pattern, as it takes a fair amount of time.  If
  2875.      there are groups, we include space for register 0 (the whole
  2876.      pattern), even though we never use it, since it simplifies the
  2877.      array indexing.  We should fix this.  */
  2878.   if (bufp->re_nsub)
  2879.     {
  2880.       regstart = REGEX_TALLOC (num_regs, const char *);
  2881.       regend = REGEX_TALLOC (num_regs, const char *);
  2882.       old_regstart = REGEX_TALLOC (num_regs, const char *);
  2883.       old_regend = REGEX_TALLOC (num_regs, const char *);
  2884.       best_regstart = REGEX_TALLOC (num_regs, const char *);
  2885.       best_regend = REGEX_TALLOC (num_regs, const char *);
  2886.       reg_info = REGEX_TALLOC (num_regs, register_info_type);
  2887.       reg_dummy = REGEX_TALLOC (num_regs, const char *);
  2888.       reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
  2889.  
  2890.       if (!(regstart && regend && old_regstart && old_regend && reg_info 
  2891.             && best_regstart && best_regend && reg_dummy && reg_info_dummy)) 
  2892.         {
  2893.           FREE_VARIABLES ();
  2894.           return -2;
  2895.         }
  2896.     }
  2897. #ifdef REGEX_MALLOC
  2898.   else
  2899.     {
  2900.       /* We must initialize all our variables to NULL, so that
  2901.          `FREE_VARIABLES' doesn't try to free them.  */
  2902.       regstart = regend = old_regstart = old_regend = best_regstart
  2903.         = best_regend = reg_dummy = NULL;
  2904.       reg_info = reg_info_dummy = (register_info_type *) NULL;
  2905.     }
  2906. #endif /* REGEX_MALLOC */
  2907.  
  2908.   /* The starting position is bogus.  */
  2909.   if (pos < 0 || pos > size1 + size2)
  2910.     {
  2911.       FREE_VARIABLES ();
  2912.       return -1;
  2913.     }
  2914.     
  2915.   /* Initialize subexpression text positions to -1 to mark ones that no
  2916.      start_memory/stop_memory has been seen for. Also initialize the
  2917.      register information struct.  */
  2918.   for (mcnt = 1; mcnt < num_regs; mcnt++)
  2919.     {
  2920.       regstart[mcnt] = regend[mcnt] 
  2921.         = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
  2922.         
  2923.       REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
  2924.       IS_ACTIVE (reg_info[mcnt]) = 0;
  2925.       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  2926.       EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  2927.     }
  2928.   
  2929.   /* We move `string1' into `string2' if the latter's empty -- but not if
  2930.      `string1' is null.  */
  2931.   if (size2 == 0 && string1 != NULL)
  2932.     {
  2933.       string2 = string1;
  2934.       size2 = size1;
  2935.       string1 = 0;
  2936.       size1 = 0;
  2937.     }
  2938.   end1 = string1 + size1;
  2939.   end2 = string2 + size2;
  2940.  
  2941.   /* Compute where to stop matching, within the two strings.  */
  2942.   if (stop <= size1)
  2943.     {
  2944.       end_match_1 = string1 + stop;
  2945.       end_match_2 = string2;
  2946.     }
  2947.   else
  2948.     {
  2949.       end_match_1 = end1;
  2950.       end_match_2 = string2 + stop - size1;
  2951.     }
  2952.  
  2953.   /* `p' scans through the pattern as `d' scans through the data. 
  2954.      `dend' is the end of the input string that `d' points within.  `d'
  2955.      is advanced into the following input string whenever necessary, but
  2956.      this happens before fetching; therefore, at the beginning of the
  2957.      loop, `d' can be pointing at the end of a string, but it cannot
  2958.      equal `string2'.  */
  2959.   if (size1 > 0 && pos <= size1)
  2960.     {
  2961.       d = string1 + pos;
  2962.       dend = end_match_1;
  2963.     }
  2964.   else
  2965.     {
  2966.       d = string2 + pos - size1;
  2967.       dend = end_match_2;
  2968.     }
  2969.  
  2970.   
  2971.   /* This loops over pattern commands.  It exits by returning from the
  2972.      function if the match is complete, or it drops through if the match
  2973.      fails at this starting point in the input data.  */
  2974.   for (;;)
  2975.     {
  2976.  
  2977.       if (p == pend)
  2978.     { /* End of pattern means we might have succeeded.  */
  2979.           
  2980.       /* If we haven't matched the entire string, and we want the
  2981.              longest match, try backtracking.  */
  2982.           if (d != end_match_2)
  2983.         {
  2984.               
  2985.               if (!FAIL_STACK_EMPTY ())
  2986.                 { /* More failure points to try.  */
  2987.                   boolean same_str_p = (FIRST_STRING_P (match_end) 
  2988.                                 == MATCHING_IN_FIRST_STRING);
  2989.  
  2990.                   /* If exceeds best match so far, save it.  */
  2991.                   if (!best_regs_set
  2992.                       || (same_str_p && d > match_end)
  2993.                       || (!same_str_p && !MATCHING_IN_FIRST_STRING))
  2994.                     {
  2995.                       best_regs_set = true;
  2996.                       match_end = d;
  2997.                       
  2998.                       
  2999.                       for (mcnt = 1; mcnt < num_regs; mcnt++)
  3000.                         {
  3001.                           best_regstart[mcnt] = regstart[mcnt];
  3002.                           best_regend[mcnt] = regend[mcnt];
  3003.                         }
  3004.                     }
  3005.                   goto fail;           
  3006.                 }
  3007.  
  3008.               /* If no failure points, don't restore garbage.  */
  3009.               else if (best_regs_set)   
  3010.                 {
  3011.               restore_best_regs:
  3012.                   /* Restore best match.  It may happen that `dend ==
  3013.                      end_match_1' while the restored d is in string2.
  3014.                      For example, the pattern `x.*y.*z' against the
  3015.                      strings `x-' and `y-z-', if the two strings are
  3016.                      not consecutive in memory.  */
  3017.                   
  3018.                   d = match_end;
  3019.                   dend = ((d >= string1 && d <= end1)
  3020.                    ? end_match_1 : end_match_2);
  3021.  
  3022.           for (mcnt = 1; mcnt < num_regs; mcnt++)
  3023.             {
  3024.               regstart[mcnt] = best_regstart[mcnt];
  3025.               regend[mcnt] = best_regend[mcnt];
  3026.             }
  3027.                 }
  3028.             } /* d != end_match_2 */
  3029.  
  3030.  
  3031.           /* If caller wants register contents data back, do it.  */
  3032.           if (regs && !bufp->no_sub)
  3033.         {
  3034.               /* Have the register data arrays been allocated?  */
  3035.               if (bufp->regs_allocated == REGS_UNALLOCATED)
  3036.                 { /* No.  So allocate them with malloc.  We need one
  3037.                      extra element beyond `num_regs' for the `-1' marker
  3038.                      GNU code uses.  */
  3039.                   regs->num_regs = MAX (RE_NREGS, num_regs + 1);
  3040.                   regs->start = TALLOC (regs->num_regs, regoff_t);
  3041.                   regs->end = TALLOC (regs->num_regs, regoff_t);
  3042.                   if (regs->start == NULL || regs->end == NULL)
  3043.                     return -2;
  3044.                   bufp->regs_allocated = REGS_REALLOCATE;
  3045.                 }
  3046.               else if (bufp->regs_allocated == REGS_REALLOCATE)
  3047.                 { /* Yes.  If we need more elements than were already
  3048.                      allocated, reallocate them.  If we need fewer, just
  3049.                      leave it alone.  */
  3050.                   if (regs->num_regs < num_regs + 1)
  3051.                     {
  3052.                       regs->num_regs = num_regs + 1;
  3053.                       RETALLOC (regs->start, regs->num_regs, regoff_t);
  3054.                       RETALLOC (regs->end, regs->num_regs, regoff_t);
  3055.                       if (regs->start == NULL || regs->end == NULL)
  3056.                         return -2;
  3057.                     }
  3058.                 }
  3059.               else
  3060. /*                assert (bufp->regs_allocated == REGS_FIXED);*/
  3061.  
  3062.               /* Convert the pointer data in `regstart' and `regend' to
  3063.                  indices.  Register zero has to be set differently,
  3064.                  since we haven't kept track of any info for it.  */
  3065.               if (regs->num_regs > 0)
  3066.                 {
  3067.                   regs->start[0] = pos;
  3068.                   regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
  3069.                       : d - string2 + size1);
  3070.                 }
  3071.               
  3072.               /* Go through the first `min (num_regs, regs->num_regs)'
  3073.                  registers, since that is all we initialized.  */
  3074.           for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
  3075.         {
  3076.                   if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
  3077.                     regs->start[mcnt] = regs->end[mcnt] = -1;
  3078.                   else
  3079.                     {
  3080.               regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
  3081.                       regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
  3082.                     }
  3083.         }
  3084.               
  3085.               /* If the regs structure we return has more elements than
  3086.                  were in the pattern, set the extra elements to -1.  If
  3087.                  we (re)allocated the registers, this is the case,
  3088.                  because we always allocate enough to have at least one
  3089.                  -1 at the end.  */
  3090.               for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
  3091.                 regs->start[mcnt] = regs->end[mcnt] = -1;
  3092.         } /* regs && !bufp->no_sub */
  3093.  
  3094.           FREE_VARIABLES ();
  3095.  
  3096.           mcnt = d - pos - (MATCHING_IN_FIRST_STRING 
  3097.                 ? string1 
  3098.                 : string2 - size1);
  3099.  
  3100.  
  3101.           return mcnt;
  3102.         }
  3103.  
  3104.       /* Otherwise match next pattern command.  */
  3105. #ifdef SWITCH_ENUM_BUG
  3106.       switch ((int) ((re_opcode_t) *p++))
  3107. #else
  3108.       switch ((re_opcode_t) *p++)
  3109. #endif
  3110.     {
  3111.         /* Ignore these.  Used to ignore the n of succeed_n's which
  3112.            currently have n == 0.  */
  3113.         case no_op:
  3114.           break;
  3115.  
  3116.  
  3117.         /* Match the next n pattern characters exactly.  The following
  3118.            byte in the pattern defines n, and the n bytes after that
  3119.            are the characters to match.  */
  3120.     case exactn:
  3121.       mcnt = *p++;
  3122.  
  3123.           /* This is written out as an if-else so we don't waste time
  3124.              testing `translate' inside the loop.  */
  3125.           if (translate)
  3126.         {
  3127.           do
  3128.         {
  3129.           PREFETCH ();
  3130.           if (translate[(unsigned char) *d++] != (char) *p++)
  3131.                     goto fail;
  3132.         }
  3133.           while (--mcnt);
  3134.         }
  3135.       else
  3136.         {
  3137.           do
  3138.         {
  3139.           PREFETCH ();
  3140.           if (*d++ != (char) *p++) goto fail;
  3141.         }
  3142.           while (--mcnt);
  3143.         }
  3144.       SET_REGS_MATCHED ();
  3145.           break;
  3146.  
  3147.  
  3148.         /* Match any character except possibly a newline or a null.  */
  3149.     case anychar:
  3150.  
  3151.           PREFETCH ();
  3152.  
  3153.           if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
  3154.               || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
  3155.         goto fail;
  3156.  
  3157.           SET_REGS_MATCHED ();
  3158.           d++;
  3159.       break;
  3160.  
  3161.  
  3162.     case charset:
  3163.     case charset_not:
  3164.       {
  3165.         register unsigned char c;
  3166.         boolean not = (re_opcode_t) *(p - 1) == charset_not;
  3167.  
  3168.  
  3169.         PREFETCH ();
  3170.         c = TRANSLATE (*d); /* The character to match.  */
  3171.  
  3172.             /* Cast to `unsigned' instead of `unsigned char' in case the
  3173.                bit list is a full 32 bytes long.  */
  3174.         if (c < (unsigned) (*p * BYTEWIDTH)
  3175.         && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  3176.           not = !not;
  3177.  
  3178.         p += 1 + *p;
  3179.  
  3180.         if (!not) goto fail;
  3181.             
  3182.         SET_REGS_MATCHED ();
  3183.             d++;
  3184.         break;
  3185.       }
  3186.  
  3187.  
  3188.         /* The beginning of a group is represented by start_memory.
  3189.            The arguments are the register number in the next byte, and the
  3190.            number of groups inner to this one in the next.  The text
  3191.            matched within the group is recorded (in the internal
  3192.            registers data structure) under the register number.  */
  3193.         case start_memory:
  3194.  
  3195.           /* Find out if this group can match the empty string.  */
  3196.       p1 = p;        /* To send to group_match_null_string_p.  */
  3197.           
  3198.           if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
  3199.             REG_MATCH_NULL_STRING_P (reg_info[*p]) 
  3200.               = group_match_null_string_p (&p1, pend, reg_info);
  3201.  
  3202.           /* Save the position in the string where we were the last time
  3203.              we were at this open-group operator in case the group is
  3204.              operated upon by a repetition operator, e.g., with `(a*)*b'
  3205.              against `ab'; then we want to ignore where we are now in
  3206.              the string in case this attempt to match fails.  */
  3207.           old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  3208.                              ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
  3209.                              : regstart[*p];
  3210.  
  3211.           regstart[*p] = d;
  3212.  
  3213.           IS_ACTIVE (reg_info[*p]) = 1;
  3214.           MATCHED_SOMETHING (reg_info[*p]) = 0;
  3215.           
  3216.           /* This is the new highest active register.  */
  3217.           highest_active_reg = *p;
  3218.           
  3219.           /* If nothing was active before, this is the new lowest active
  3220.              register.  */
  3221.           if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  3222.             lowest_active_reg = *p;
  3223.  
  3224.           /* Move past the register number and inner group count.  */
  3225.           p += 2;
  3226.           break;
  3227.  
  3228.  
  3229.         /* The stop_memory opcode represents the end of a group.  Its
  3230.            arguments are the same as start_memory's: the register
  3231.            number, and the number of inner groups.  */
  3232.     case stop_memory:
  3233.              
  3234.           /* We need to save the string position the last time we were at
  3235.              this close-group operator in case the group is operated
  3236.              upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
  3237.              against `aba'; then we want to ignore where we are now in
  3238.              the string in case this attempt to match fails.  */
  3239.           old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  3240.                            ? REG_UNSET (regend[*p]) ? d : regend[*p]
  3241.                : regend[*p];
  3242.  
  3243.           regend[*p] = d;
  3244.  
  3245.           /* This register isn't active anymore.  */
  3246.           IS_ACTIVE (reg_info[*p]) = 0;
  3247.           
  3248.           /* If this was the only register active, nothing is active
  3249.              anymore.  */
  3250.           if (lowest_active_reg == highest_active_reg)
  3251.             {
  3252.               lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3253.               highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3254.             }
  3255.           else
  3256.             { /* We must scan for the new highest active register, since
  3257.                  it isn't necessarily one less than now: consider
  3258.                  (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
  3259.                  new highest active register is 1.  */
  3260.               unsigned char r = *p - 1;
  3261.               while (r > 0 && !IS_ACTIVE (reg_info[r]))
  3262.                 r--;
  3263.               
  3264.               /* If we end up at register zero, that means that we saved
  3265.                  the registers as the result of an `on_failure_jump', not
  3266.                  a `start_memory', and we jumped to past the innermost
  3267.                  `stop_memory'.  For example, in ((.)*) we save
  3268.                  registers 1 and 2 as a result of the *, but when we pop
  3269.                  back to the second ), we are at the stop_memory 1.
  3270.                  Thus, nothing is active.  */
  3271.           if (r == 0)
  3272.                 {
  3273.                   lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3274.                   highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3275.                 }
  3276.               else
  3277.                 highest_active_reg = r;
  3278.             }
  3279.           
  3280.           /* If just failed to match something this time around with a
  3281.              group that's operated on by a repetition operator, try to
  3282.              force exit from the ``loop'', and restore the register
  3283.              information for this group that we had before trying this
  3284.              last match.  */
  3285.           if ((!MATCHED_SOMETHING (reg_info[*p])
  3286.                || (re_opcode_t) p[-3] == start_memory)
  3287.           && (p + 2) < pend)              
  3288.             {
  3289.               boolean is_a_jump_n = false;
  3290.               
  3291.               p1 = p + 2;
  3292.               mcnt = 0;
  3293.               switch ((re_opcode_t) *p1++)
  3294.                 {
  3295.                   case jump_n:
  3296.             is_a_jump_n = true;
  3297.                   case pop_failure_jump:
  3298.           case maybe_pop_jump:
  3299.           case jump:
  3300.           case dummy_failure_jump:
  3301.                     EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3302.             if (is_a_jump_n)
  3303.               p1 += 2;
  3304.                     break;
  3305.                   
  3306.                   default:
  3307.                     /* do nothing */ ;
  3308.                 }
  3309.           p1 += mcnt;
  3310.         
  3311.               /* If the next operation is a jump backwards in the pattern
  3312.              to an on_failure_jump right before the start_memory
  3313.                  corresponding to this stop_memory, exit from the loop
  3314.                  by forcing a failure after pushing on the stack the
  3315.                  on_failure_jump's jump in the pattern, and d.  */
  3316.               if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
  3317.                   && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
  3318.         {
  3319.                   /* If this group ever matched anything, then restore
  3320.                      what its registers were before trying this last
  3321.                      failed match, e.g., with `(a*)*b' against `ab' for
  3322.                      regstart[1], and, e.g., with `((a*)*(b*)*)*'
  3323.                      against `aba' for regend[3].
  3324.                      
  3325.                      Also restore the registers for inner groups for,
  3326.                      e.g., `((a*)(b*))*' against `aba' (register 3 would
  3327.                      otherwise get trashed).  */
  3328.                      
  3329.                   if (EVER_MATCHED_SOMETHING (reg_info[*p]))
  3330.             {
  3331.               unsigned r; 
  3332.         
  3333.                       EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
  3334.                       
  3335.               /* Restore this and inner groups' (if any) registers.  */
  3336.                       for (r = *p; r < *p + *(p + 1); r++)
  3337.                         {
  3338.                           regstart[r] = old_regstart[r];
  3339.  
  3340.                           /* xx why this test?  */
  3341.                           if ((int) old_regend[r] >= (int) regstart[r])
  3342.                             regend[r] = old_regend[r];
  3343.                         }     
  3344.                     }
  3345.           p1++;
  3346.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3347.                   PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
  3348.  
  3349.                   goto fail;
  3350.                 }
  3351.             }
  3352.           
  3353.           /* Move past the register number and the inner group count.  */
  3354.           p += 2;
  3355.           break;
  3356.  
  3357.  
  3358.     /* \<digit> has been turned into a `duplicate' command which is
  3359.            followed by the numeric value of <digit> as the register number.  */
  3360.         case duplicate:
  3361.       {
  3362.         register const char *d2, *dend2;
  3363.         int regno = *p++;   /* Get which register to match against.  */
  3364.  
  3365.         /* Can't back reference a group which we've never matched.  */
  3366.             if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
  3367.               goto fail;
  3368.               
  3369.             /* Where in input to try to start matching.  */
  3370.             d2 = regstart[regno];
  3371.             
  3372.             /* Where to stop matching; if both the place to start and
  3373.                the place to stop matching are in the same string, then
  3374.                set to the place to stop, otherwise, for now have to use
  3375.                the end of the first string.  */
  3376.  
  3377.             dend2 = ((FIRST_STRING_P (regstart[regno]) 
  3378.               == FIRST_STRING_P (regend[regno]))
  3379.              ? regend[regno] : end_match_1);
  3380.         for (;;)
  3381.           {
  3382.         /* If necessary, advance to next segment in register
  3383.                    contents.  */
  3384.         while (d2 == dend2)
  3385.           {
  3386.             if (dend2 == end_match_2) break;
  3387.             if (dend2 == regend[regno]) break;
  3388.  
  3389.                     /* End of string1 => advance to string2. */
  3390.                     d2 = string2;
  3391.                     dend2 = regend[regno];
  3392.           }
  3393.         /* At end of register contents => success */
  3394.         if (d2 == dend2) break;
  3395.  
  3396.         /* If necessary, advance to next segment in data.  */
  3397.         PREFETCH ();
  3398.  
  3399.         /* How many characters left in this segment to match.  */
  3400.         mcnt = dend - d;
  3401.                 
  3402.         /* Want how many consecutive characters we can match in
  3403.                    one shot, so, if necessary, adjust the count.  */
  3404.                 if (mcnt > dend2 - d2)
  3405.           mcnt = dend2 - d2;
  3406.                   
  3407.         /* Compare that many; failure if mismatch, else move
  3408.                    past them.  */
  3409.         if (translate 
  3410.                     ? bcmp_translate (d, d2, mcnt, translate) 
  3411.                     : bcmp (d, d2, mcnt))
  3412.           goto fail;
  3413.         d += mcnt, d2 += mcnt;
  3414.           }
  3415.       }
  3416.       break;
  3417.  
  3418.  
  3419.         /* begline matches the empty string at the beginning of the string
  3420.            (unless `not_bol' is set in `bufp'), and, if
  3421.            `newline_anchor' is set, after newlines.  */
  3422.     case begline:
  3423.           
  3424.           if (AT_STRINGS_BEG (d))
  3425.             {
  3426.               if (!bufp->not_bol) break;
  3427.             }
  3428.           else if (d[-1] == '\n' && bufp->newline_anchor)
  3429.             {
  3430.               break;
  3431.             }
  3432.           /* In all other cases, we fail.  */
  3433.           goto fail;
  3434.  
  3435.  
  3436.         /* endline is the dual of begline.  */
  3437.     case endline:
  3438.  
  3439.           if (AT_STRINGS_END (d))
  3440.             {
  3441.               if (!bufp->not_eol) break;
  3442.             }
  3443.           
  3444.           /* We have to ``prefetch'' the next character.  */
  3445.           else if ((d == end1 ? *string2 : *d) == '\n'
  3446.                    && bufp->newline_anchor)
  3447.             {
  3448.               break;
  3449.             }
  3450.           goto fail;
  3451.  
  3452.  
  3453.     /* Match at the very beginning of the data.  */
  3454.         case begbuf:
  3455.           if (AT_STRINGS_BEG (d))
  3456.             break;
  3457.           goto fail;
  3458.  
  3459.  
  3460.     /* Match at the very end of the data.  */
  3461.         case endbuf:
  3462.       if (AT_STRINGS_END (d))
  3463.         break;
  3464.           goto fail;
  3465.  
  3466.  
  3467.         /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
  3468.            pushes NULL as the value for the string on the stack.  Then
  3469.            `pop_failure_point' will keep the current value for the
  3470.            string, instead of restoring it.  To see why, consider
  3471.            matching `foo\nbar' against `.*\n'.  The .* matches the foo;
  3472.            then the . fails against the \n.  But the next thing we want
  3473.            to do is match the \n against the \n; if we restored the
  3474.            string value, we would be back at the foo.
  3475.            
  3476.            Because this is used only in specific cases, we don't need to
  3477.            check all the things that `on_failure_jump' does, to make
  3478.            sure the right things get saved on the stack.  Hence we don't
  3479.            share its code.  The only reason to push anything on the
  3480.            stack at all is that otherwise we would have to change
  3481.            `anychar's code to do something besides goto fail in this
  3482.            case; that seems worse than this.  */
  3483.         case on_failure_keep_string_jump:
  3484.           
  3485.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3486.  
  3487.           PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
  3488.           break;
  3489.  
  3490.  
  3491.     /* Uses of on_failure_jump:
  3492.         
  3493.            Each alternative starts with an on_failure_jump that points
  3494.            to the beginning of the next alternative.  Each alternative
  3495.            except the last ends with a jump that in effect jumps past
  3496.            the rest of the alternatives.  (They really jump to the
  3497.            ending jump of the following alternative, because tensioning
  3498.            these jumps is a hassle.)
  3499.  
  3500.            Repeats start with an on_failure_jump that points past both
  3501.            the repetition text and either the following jump or
  3502.            pop_failure_jump back to this on_failure_jump.  */
  3503.     case on_failure_jump:
  3504.         on_failure:
  3505.  
  3506.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3507.  
  3508.           /* If this on_failure_jump comes right before a group (i.e.,
  3509.              the original * applied to a group), save the information
  3510.              for that group and all inner ones, so that if we fail back
  3511.              to this point, the group's information will be correct.
  3512.              For example, in \(a*\)*\1, we need the preceding group,
  3513.              and in \(\(a*\)b*\)\2, we need the inner group.  */
  3514.  
  3515.           /* We can't use `p' to check ahead because we push
  3516.              a failure point to `p + mcnt' after we do this.  */
  3517.           p1 = p;
  3518.  
  3519.           /* We need to skip no_op's before we look for the
  3520.              start_memory in case this on_failure_jump is happening as
  3521.              the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
  3522.              against aba.  */
  3523.           while (p1 < pend && (re_opcode_t) *p1 == no_op)
  3524.             p1++;
  3525.  
  3526.           if (p1 < pend && (re_opcode_t) *p1 == start_memory)
  3527.             {
  3528.               /* We have a new highest active register now.  This will
  3529.                  get reset at the start_memory we are about to get to,
  3530.                  but we will have saved all the registers relevant to
  3531.                  this repetition op, as described above.  */
  3532.               highest_active_reg = *(p1 + 1) + *(p1 + 2);
  3533.               if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  3534.                 lowest_active_reg = *(p1 + 1);
  3535.             }
  3536.  
  3537.           PUSH_FAILURE_POINT (p + mcnt, d, -2);
  3538.           break;
  3539.  
  3540.  
  3541.         /* A smart repeat ends with `maybe_pop_jump'.
  3542.        We change it to either `pop_failure_jump' or `jump'.  */
  3543.         case maybe_pop_jump:
  3544.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3545.           {
  3546.         register unsigned char *p2 = p;
  3547.  
  3548.             /* Compare the beginning of the repeat with what in the
  3549.                pattern follows its end. If we can establish that there
  3550.                is nothing that they would both match, i.e., that we
  3551.                would have to backtrack because of (as in, e.g., `a*a')
  3552.                then we can change to pop_failure_jump, because we'll
  3553.                never have to backtrack.
  3554.                
  3555.                This is not true in the case of alternatives: in
  3556.                `(a|ab)*' we do need to backtrack to the `ab' alternative
  3557.                (e.g., if the string was `ab').  But instead of trying to
  3558.                detect that here, the alternative has put on a dummy
  3559.                failure point which is what we will end up popping.  */
  3560.  
  3561.         /* Skip over open/close-group commands.  */
  3562.         while (p2 + 2 < pend
  3563.            && ((re_opcode_t) *p2 == stop_memory
  3564.                || (re_opcode_t) *p2 == start_memory))
  3565.           p2 += 3;            /* Skip over args, too.  */
  3566.  
  3567.             /* If we're at the end of the pattern, we can change.  */
  3568.             if (p2 == pend)
  3569.           {
  3570.         /* Consider what happens when matching ":\(.*\)"
  3571.            against ":/".  I don't really understand this code
  3572.            yet.  */
  3573.               p[-3] = (unsigned char) pop_failure_jump;
  3574.               }
  3575.  
  3576.             else if ((re_opcode_t) *p2 == exactn
  3577.              || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
  3578.           {
  3579.         register unsigned char c
  3580.                   = *p2 == (unsigned char) endline ? '\n' : p2[2];
  3581.         p1 = p + mcnt;
  3582.  
  3583.                 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
  3584.                    to the `maybe_finalize_jump' of this case.  Examine what 
  3585.                    follows.  */
  3586.                 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
  3587.                   {
  3588.               p[-3] = (unsigned char) pop_failure_jump;
  3589.                   }
  3590.                   
  3591.         else if ((re_opcode_t) p1[3] == charset
  3592.              || (re_opcode_t) p1[3] == charset_not)
  3593.           {
  3594.             int not = (re_opcode_t) p1[3] == charset_not;
  3595.                     
  3596.             if (c < (unsigned char) (p1[4] * BYTEWIDTH)
  3597.             && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  3598.               not = !not;
  3599.  
  3600.                     /* `not' is equal to 1 if c would match, which means
  3601.                         that we can't change to pop_failure_jump.  */
  3602.             if (!not)
  3603.                       {
  3604.                   p[-3] = (unsigned char) pop_failure_jump;
  3605.                       }
  3606.           }
  3607.           }
  3608.       }
  3609.       p -= 2;        /* Point at relative address again.  */
  3610.       if ((re_opcode_t) p[-1] != pop_failure_jump)
  3611.         {
  3612.           p[-1] = (unsigned char) jump;
  3613.           goto unconditional_jump;
  3614.         }
  3615.         /* Note fall through.  */
  3616.  
  3617.  
  3618.     /* The end of a simple repeat has a pop_failure_jump back to
  3619.            its matching on_failure_jump, where the latter will push a
  3620.            failure point.  The pop_failure_jump takes off failure
  3621.            points put on by this pop_failure_jump's matching
  3622.            on_failure_jump; we got through the pattern to here from the
  3623.            matching on_failure_jump, so didn't fail.  */
  3624.         case pop_failure_jump:
  3625.           {
  3626.             /* We need to pass separate storage for the lowest and
  3627.                highest registers, even though we don't care about the
  3628.                actual values.  Otherwise, we will restore only one
  3629.                register from the stack, since lowest will == highest in
  3630.                `pop_failure_point'.  */
  3631.             unsigned dummy_low_reg, dummy_high_reg;
  3632.             unsigned char *pdummy;
  3633.             const char *sdummy;
  3634.  
  3635.             POP_FAILURE_POINT (sdummy, pdummy,
  3636.                                dummy_low_reg, dummy_high_reg,
  3637.                                reg_dummy, reg_dummy, reg_info_dummy);
  3638.           }
  3639.           /* Note fall through.  */
  3640.  
  3641.           
  3642.         /* Unconditionally jump (without popping any failure points).  */
  3643.         case jump:
  3644.     unconditional_jump:
  3645.       EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
  3646.       p += mcnt;                /* Do the jump.  */
  3647.       break;
  3648.  
  3649.     
  3650.         /* We need this opcode so we can detect where alternatives end
  3651.            in `group_match_null_string_p' et al.  */
  3652.         case jump_past_alt:
  3653.           goto unconditional_jump;
  3654.  
  3655.  
  3656.         /* Normally, the on_failure_jump pushes a failure point, which
  3657.            then gets popped at pop_failure_jump.  We will end up at
  3658.            pop_failure_jump, also, and with a pattern of, say, `a+', we
  3659.            are skipping over the on_failure_jump, so we have to push
  3660.            something meaningless for pop_failure_jump to pop.  */
  3661.         case dummy_failure_jump:
  3662.           /* It doesn't matter what we push for the string here.  What
  3663.              the code at `fail' tests is the value for the pattern.  */
  3664.           PUSH_FAILURE_POINT (0, 0, -2);
  3665.           goto unconditional_jump;
  3666.  
  3667.  
  3668.         /* At the end of an alternative, we need to push a dummy failure
  3669.            point in case we are followed by a `pop_failure_jump', because
  3670.            we don't want the failure point for the alternative to be
  3671.            popped.  For example, matching `(a|ab)*' against `aab'
  3672.            requires that we match the `ab' alternative.  */
  3673.         case push_dummy_failure:
  3674.           /* See comments just above at `dummy_failure_jump' about the
  3675.              two zeroes.  */
  3676.           PUSH_FAILURE_POINT (0, 0, -2);
  3677.           break;
  3678.  
  3679.         /* Have to succeed matching what follows at least n times.
  3680.            After that, handle like `on_failure_jump'.  */
  3681.         case succeed_n: 
  3682.           EXTRACT_NUMBER (mcnt, p + 2);
  3683.  
  3684. /*          assert (mcnt >= 0);*/
  3685.           /* Originally, this is how many times we HAVE to succeed.  */
  3686.           if (mcnt > 0)
  3687.             {
  3688.                mcnt--;
  3689.            p += 2;
  3690.                STORE_NUMBER_AND_INCR (p, mcnt);
  3691.             }
  3692.       else if (mcnt == 0)
  3693.             {
  3694.           p[2] = (unsigned char) no_op;
  3695.               p[3] = (unsigned char) no_op;
  3696.               goto on_failure;
  3697.             }
  3698.           break;
  3699.         
  3700.         case jump_n: 
  3701.           EXTRACT_NUMBER (mcnt, p + 2);
  3702.  
  3703.           /* Originally, this is how many times we CAN jump.  */
  3704.           if (mcnt)
  3705.             {
  3706.                mcnt--;
  3707.                STORE_NUMBER (p + 2, mcnt);
  3708.            goto unconditional_jump;         
  3709.             }
  3710.           /* If don't have to jump any more, skip over the rest of command.  */
  3711.       else      
  3712.         p += 4;             
  3713.           break;
  3714.         
  3715.     case set_number_at:
  3716.       {
  3717.  
  3718.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3719.             p1 = p + mcnt;
  3720.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3721.         STORE_NUMBER (p1, mcnt);
  3722.             break;
  3723.           }
  3724.  
  3725.         case wordbound:
  3726.           if (AT_WORD_BOUNDARY (d))
  3727.         break;
  3728.           goto fail;
  3729.  
  3730.     case notwordbound:
  3731.       if (AT_WORD_BOUNDARY (d))
  3732.         goto fail;
  3733.           break;
  3734.  
  3735.     case wordbeg:
  3736.       if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
  3737.         break;
  3738.           goto fail;
  3739.  
  3740.     case wordend:
  3741.       if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
  3742.               && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
  3743.         break;
  3744.           goto fail;
  3745.  
  3746. #ifdef emacs
  3747. #ifdef emacs19
  3748.       case before_dot:
  3749.        if (PTR_CHAR_POS ((unsigned char *) d) >= point)
  3750.           goto fail;
  3751.         break;
  3752.   
  3753.       case at_dot:
  3754.        if (PTR_CHAR_POS ((unsigned char *) d) != point)
  3755.           goto fail;
  3756.         break;
  3757.   
  3758.       case after_dot:
  3759.           if (PTR_CHAR_POS ((unsigned char *) d) <= point)
  3760.           goto fail;
  3761.         break;
  3762. #else /* not emacs19 */
  3763.     case at_dot:
  3764.       if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
  3765.         goto fail;
  3766.       break;
  3767. #endif /* not emacs19 */
  3768.  
  3769.     case syntaxspec:
  3770.       mcnt = *p++;
  3771.       goto matchsyntax;
  3772.  
  3773.         case wordchar:
  3774.       mcnt = (int) Sword;
  3775.         matchsyntax:
  3776.       PREFETCH ();
  3777.       if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
  3778.             goto fail;
  3779.           SET_REGS_MATCHED ();
  3780.       break;
  3781.  
  3782.     case notsyntaxspec:
  3783.       mcnt = *p++;
  3784.       goto matchnotsyntax;
  3785.  
  3786.         case notwordchar:
  3787.       mcnt = (int) Sword;
  3788.         matchnotsyntax:
  3789.       PREFETCH ();
  3790.       if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
  3791.             goto fail;
  3792.       SET_REGS_MATCHED ();
  3793.           break;
  3794.  
  3795. #else /* not emacs */
  3796.     case wordchar:
  3797.       PREFETCH ();
  3798.           if (!WORDCHAR_P (d))
  3799.             goto fail;
  3800.       SET_REGS_MATCHED ();
  3801.           d++;
  3802.       break;
  3803.       
  3804.     case notwordchar:
  3805.       PREFETCH ();
  3806.       if (WORDCHAR_P (d))
  3807.             goto fail;
  3808.           SET_REGS_MATCHED ();
  3809.           d++;
  3810.       break;
  3811. #endif /* not emacs */
  3812.           
  3813.         default:
  3814.           abort ();
  3815.     }
  3816.       continue;  /* Successfully executed one pattern command; keep going.  */
  3817.  
  3818.  
  3819.     /* We goto here if a matching operation fails. */
  3820.     fail:
  3821.       if (!FAIL_STACK_EMPTY ())
  3822.     { /* A restart point is known.  Restore to that state.  */
  3823.           POP_FAILURE_POINT (d, p,
  3824.                              lowest_active_reg, highest_active_reg,
  3825.                              regstart, regend, reg_info);
  3826.  
  3827.           /* If this failure point is a dummy, try the next one.  */
  3828.           if (!p)
  3829.         goto fail;
  3830.  
  3831.           /* If we failed to the end of the pattern, don't examine *p.  */
  3832. /*      assert (p <= pend);*/
  3833.           if (p < pend)
  3834.             {
  3835.               boolean is_a_jump_n = false;
  3836.               
  3837.               /* If failed to a backwards jump that's part of a repetition
  3838.                  loop, need to pop this failure point and use the next one.  */
  3839.               switch ((re_opcode_t) *p)
  3840.                 {
  3841.                 case jump_n:
  3842.                   is_a_jump_n = true;
  3843.                 case maybe_pop_jump:
  3844.                 case pop_failure_jump:
  3845.                 case jump:
  3846.                   p1 = p + 1;
  3847.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3848.                   p1 += mcnt;    
  3849.  
  3850.                   if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
  3851.                       || (!is_a_jump_n
  3852.                           && (re_opcode_t) *p1 == on_failure_jump))
  3853.                     goto fail;
  3854.                   break;
  3855.                 default:
  3856.                   /* do nothing */ ;
  3857.                 }
  3858.             }
  3859.  
  3860.           if (d >= string1 && d <= end1)
  3861.         dend = end_match_1;
  3862.         }
  3863.       else
  3864.         break;   /* Matching at this starting point really fails.  */
  3865.     } /* for (;;) */
  3866.  
  3867.   if (best_regs_set)
  3868.     goto restore_best_regs;
  3869.  
  3870.   FREE_VARIABLES ();
  3871.  
  3872.   return -1;                     /* Failure to match.  */
  3873. } /* re_match_2 */
  3874.  
  3875. /* Subroutine definitions for re_match_2.  */
  3876.  
  3877.  
  3878. /* We are passed P pointing to a register number after a start_memory.
  3879.    
  3880.    Return true if the pattern up to the corresponding stop_memory can
  3881.    match the empty string, and false otherwise.
  3882.    
  3883.    If we find the matching stop_memory, sets P to point to one past its number.
  3884.    Otherwise, sets P to an undefined byte less than or equal to END.
  3885.  
  3886.    We don't handle duplicates properly (yet).  */
  3887.  
  3888. static boolean
  3889. group_match_null_string_p (p, end, reg_info)
  3890.     unsigned char **p, *end;
  3891.     register_info_type *reg_info;
  3892. {
  3893.   int mcnt;
  3894.   /* Point to after the args to the start_memory.  */
  3895.   unsigned char *p1 = *p + 2;
  3896.   
  3897.   while (p1 < end)
  3898.     {
  3899.       /* Skip over opcodes that can match nothing, and return true or
  3900.      false, as appropriate, when we get to one that can't, or to the
  3901.          matching stop_memory.  */
  3902.       
  3903.       switch ((re_opcode_t) *p1)
  3904.         {
  3905.         /* Could be either a loop or a series of alternatives.  */
  3906.         case on_failure_jump:
  3907.           p1++;
  3908.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3909.           
  3910.           /* If the next operation is not a jump backwards in the
  3911.          pattern.  */
  3912.  
  3913.       if (mcnt >= 0)
  3914.         {
  3915.               /* Go through the on_failure_jumps of the alternatives,
  3916.                  seeing if any of the alternatives cannot match nothing.
  3917.                  The last alternative starts with only a jump,
  3918.                  whereas the rest start with on_failure_jump and end
  3919.                  with a jump, e.g., here is the pattern for `a|b|c':
  3920.  
  3921.                  /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
  3922.                  /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
  3923.                  /exactn/1/c                        
  3924.  
  3925.                  So, we have to first go through the first (n-1)
  3926.                  alternatives and then deal with the last one separately.  */
  3927.  
  3928.  
  3929.               /* Deal with the first (n-1) alternatives, which start
  3930.                  with an on_failure_jump (see above) that jumps to right
  3931.                  past a jump_past_alt.  */
  3932.  
  3933.               while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
  3934.                 {
  3935.                   /* `mcnt' holds how many bytes long the alternative
  3936.                      is, including the ending `jump_past_alt' and
  3937.                      its number.  */
  3938.  
  3939.                   if (!alt_match_null_string_p (p1, p1 + mcnt - 3, 
  3940.                                       reg_info))
  3941.                     return false;
  3942.  
  3943.                   /* Move to right after this alternative, including the
  3944.              jump_past_alt.  */
  3945.                   p1 += mcnt;    
  3946.  
  3947.                   /* Break if it's the beginning of an n-th alternative
  3948.                      that doesn't begin with an on_failure_jump.  */
  3949.                   if ((re_opcode_t) *p1 != on_failure_jump)
  3950.                     break;
  3951.         
  3952.           /* Still have to check that it's not an n-th
  3953.              alternative that starts with an on_failure_jump.  */
  3954.           p1++;
  3955.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3956.                   if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
  3957.                     {
  3958.               /* Get to the beginning of the n-th alternative.  */
  3959.                       p1 -= 3;
  3960.                       break;
  3961.                     }
  3962.                 }
  3963.  
  3964.               /* Deal with the last alternative: go back and get number
  3965.                  of the `jump_past_alt' just before it.  `mcnt' contains
  3966.                  the length of the alternative.  */
  3967.               EXTRACT_NUMBER (mcnt, p1 - 2);
  3968.  
  3969.               if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
  3970.                 return false;
  3971.  
  3972.               p1 += mcnt;    /* Get past the n-th alternative.  */
  3973.             } /* if mcnt > 0 */
  3974.           break;
  3975.  
  3976.           
  3977.         case stop_memory:
  3978. /*      assert (p1[1] == **p);*/
  3979.           *p = p1 + 2;
  3980.           return true;
  3981.  
  3982.         
  3983.         default: 
  3984.           if (!common_op_match_null_string_p (&p1, end, reg_info))
  3985.             return false;
  3986.         }
  3987.     } /* while p1 < end */
  3988.  
  3989.   return false;
  3990. } /* group_match_null_string_p */
  3991.  
  3992.  
  3993. /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
  3994.    It expects P to be the first byte of a single alternative and END one
  3995.    byte past the last. The alternative can contain groups.  */
  3996.    
  3997. static boolean
  3998. alt_match_null_string_p (p, end, reg_info)
  3999.     unsigned char *p, *end;
  4000.     register_info_type *reg_info;
  4001. {
  4002.   int mcnt;
  4003.   unsigned char *p1 = p;
  4004.   
  4005.   while (p1 < end)
  4006.     {
  4007.       /* Skip over opcodes that can match nothing, and break when we get 
  4008.          to one that can't.  */
  4009.       
  4010.       switch ((re_opcode_t) *p1)
  4011.         {
  4012.     /* It's a loop.  */
  4013.         case on_failure_jump:
  4014.           p1++;
  4015.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4016.           p1 += mcnt;
  4017.           break;
  4018.           
  4019.     default: 
  4020.           if (!common_op_match_null_string_p (&p1, end, reg_info))
  4021.             return false;
  4022.         }
  4023.     }  /* while p1 < end */
  4024.  
  4025.   return true;
  4026. } /* alt_match_null_string_p */
  4027.  
  4028.  
  4029. /* Deals with the ops common to group_match_null_string_p and
  4030.    alt_match_null_string_p.  
  4031.    
  4032.    Sets P to one after the op and its arguments, if any.  */
  4033.  
  4034. static boolean
  4035. common_op_match_null_string_p (p, end, reg_info)
  4036.     unsigned char **p, *end;
  4037.     register_info_type *reg_info;
  4038. {
  4039.   int mcnt;
  4040.   boolean ret;
  4041.   int reg_no;
  4042.   unsigned char *p1 = *p;
  4043.  
  4044.   switch ((re_opcode_t) *p1++)
  4045.     {
  4046.     case no_op:
  4047.     case begline:
  4048.     case endline:
  4049.     case begbuf:
  4050.     case endbuf:
  4051.     case wordbeg:
  4052.     case wordend:
  4053.     case wordbound:
  4054.     case notwordbound:
  4055. #ifdef emacs
  4056.     case before_dot:
  4057.     case at_dot:
  4058.     case after_dot:
  4059. #endif
  4060.       break;
  4061.  
  4062.     case start_memory:
  4063.       reg_no = *p1;
  4064. /*      assert (reg_no > 0 && reg_no <= MAX_REGNUM);*/
  4065.       ret = group_match_null_string_p (&p1, end, reg_info);
  4066.       
  4067.       /* Have to set this here in case we're checking a group which
  4068.          contains a group and a back reference to it.  */
  4069.  
  4070.       if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
  4071.         REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
  4072.  
  4073.       if (!ret)
  4074.         return false;
  4075.       break;
  4076.           
  4077.     /* If this is an optimized succeed_n for zero times, make the jump.  */
  4078.     case jump:
  4079.       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4080.       if (mcnt >= 0)
  4081.         p1 += mcnt;
  4082.       else
  4083.         return false;
  4084.       break;
  4085.  
  4086.     case succeed_n:
  4087.       /* Get to the number of times to succeed.  */
  4088.       p1 += 2;        
  4089.       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4090.  
  4091.       if (mcnt == 0)
  4092.         {
  4093.           p1 -= 4;
  4094.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4095.           p1 += mcnt;
  4096.         }
  4097.       else
  4098.         return false;
  4099.       break;
  4100.  
  4101.     case duplicate: 
  4102.       if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
  4103.         return false;
  4104.       break;
  4105.  
  4106.     case set_number_at:
  4107.       p1 += 4;
  4108.  
  4109.     default:
  4110.       /* All other opcodes mean we cannot match the empty string.  */
  4111.       return false;
  4112.   }
  4113.  
  4114.   *p = p1;
  4115.   return true;
  4116. } /* common_op_match_null_string_p */
  4117.  
  4118.  
  4119. /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
  4120.    bytes; nonzero otherwise.  */
  4121.    
  4122. static int
  4123. bcmp_translate (s1, s2, len, translate)
  4124.      unsigned char *s1, *s2;
  4125.      register int len;
  4126.      char *translate;
  4127. {
  4128.   register unsigned char *p1 = s1, *p2 = s2;
  4129.   while (len)
  4130.     {
  4131.       if (translate[*p1++] != translate[*p2++]) return 1;
  4132.       len--;
  4133.     }
  4134.   return 0;
  4135. }
  4136.  
  4137. /* Entry points for GNU code.  */
  4138.  
  4139. /* re_compile_pattern is the GNU regular expression compiler: it
  4140.    compiles PATTERN (of length SIZE) and puts the result in BUFP.
  4141.    Returns 0 if the pattern was valid, otherwise an error string.
  4142.    
  4143.    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  4144.    are set in BUFP on entry.
  4145.    
  4146.    We call regex_compile to do the actual compilation.  */
  4147.  
  4148. const char *
  4149. re_compile_pattern (pattern, length, bufp)
  4150.      const char *pattern;
  4151.      int length;
  4152.      struct re_pattern_buffer *bufp;
  4153. {
  4154.   reg_errcode_t ret;
  4155.   
  4156.   /* GNU code is written to assume at least RE_NREGS registers will be set
  4157.      (and at least one extra will be -1).  */
  4158.   bufp->regs_allocated = REGS_UNALLOCATED;
  4159.   
  4160.   /* And GNU code determines whether or not to get register information
  4161.      by passing null for the REGS argument to re_match, etc., not by
  4162.      setting no_sub.  */
  4163.   bufp->no_sub = 0;
  4164.   
  4165.   /* Match anchors at newline.  */
  4166.   bufp->newline_anchor = 1;
  4167.   
  4168.   ret = regex_compile (pattern, length, re_syntax_options, bufp);
  4169.  
  4170.   return re_error_msg[(int) ret];
  4171. }     
  4172.  
  4173. /* Entry points compatible with 4.2 BSD regex library.  We don't define
  4174.    them if this is an Emacs or POSIX compilation.  */
  4175.  
  4176. #if !defined (emacs) && !defined (_POSIX_SOURCE)
  4177.  
  4178. /* BSD has one and only one pattern buffer.  */
  4179. static struct re_pattern_buffer re_comp_buf;
  4180.  
  4181. char *
  4182. re_comp (s)
  4183.     const char *s;
  4184. {
  4185.   reg_errcode_t ret;
  4186.   
  4187.   if (!s)
  4188.     {
  4189.       if (!re_comp_buf.buffer)
  4190.     return "No previous regular expression";
  4191.       return 0;
  4192.     }
  4193.  
  4194.   if (!re_comp_buf.buffer)
  4195.     {
  4196.       re_comp_buf.buffer = (unsigned char *) malloc (200);
  4197.       if (re_comp_buf.buffer == NULL)
  4198.         return "Memory exhausted";
  4199.       re_comp_buf.allocated = 200;
  4200.  
  4201.       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
  4202.       if (re_comp_buf.fastmap == NULL)
  4203.     return "Memory exhausted";
  4204.     }
  4205.  
  4206.   /* Since `re_exec' always passes NULL for the `regs' argument, we
  4207.      don't need to initialize the pattern buffer fields which affect it.  */
  4208.  
  4209.   /* Match anchors at newlines.  */
  4210.   re_comp_buf.newline_anchor = 1;
  4211.  
  4212.   ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
  4213.   
  4214.   /* Yes, we're discarding `const' here.  */
  4215.   return (char *) re_error_msg[(int) ret];
  4216. }
  4217.  
  4218.  
  4219. int
  4220. re_exec (s)
  4221.     const char *s;
  4222. {
  4223.   const int len = strlen (s);
  4224.   return
  4225.     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
  4226. }
  4227. #endif /* not emacs and not _POSIX_SOURCE */
  4228.  
  4229. /* POSIX.2 functions.  Don't define these for Emacs.  */
  4230.  
  4231. #ifndef emacs
  4232.  
  4233. /* regcomp takes a regular expression as a string and compiles it.
  4234.  
  4235.    PREG is a regex_t *.  We do not expect any fields to be initialized,
  4236.    since POSIX says we shouldn't.  Thus, we set
  4237.  
  4238.      `buffer' to the compiled pattern;
  4239.      `used' to the length of the compiled pattern;
  4240.      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  4241.        REG_EXTENDED bit in CFLAGS is set; otherwise, to
  4242.        RE_SYNTAX_POSIX_BASIC;
  4243.      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  4244.      `fastmap' and `fastmap_accurate' to zero;
  4245.      `re_nsub' to the number of subexpressions in PATTERN.
  4246.  
  4247.    PATTERN is the address of the pattern string.
  4248.  
  4249.    CFLAGS is a series of bits which affect compilation.
  4250.  
  4251.      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  4252.      use POSIX basic syntax.
  4253.  
  4254.      If REG_NEWLINE is set, then . and [^...] don't match newline.
  4255.      Also, regexec will try a match beginning after every newline.
  4256.  
  4257.      If REG_ICASE is set, then we considers upper- and lowercase
  4258.      versions of letters to be equivalent when matching.
  4259.  
  4260.      If REG_NOSUB is set, then when PREG is passed to regexec, that
  4261.      routine will report only success or failure, and nothing about the
  4262.      registers.
  4263.  
  4264.    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
  4265.    the return codes and their meanings.)  */
  4266.  
  4267. int
  4268. regcomp (preg, pattern, cflags)
  4269.     regex_t *preg;
  4270.     const char *pattern; 
  4271.     int cflags;
  4272. {
  4273.   reg_errcode_t ret;
  4274.   unsigned syntax
  4275.     = (cflags & REG_EXTENDED) ?
  4276.       RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
  4277.  
  4278.   /* regex_compile will allocate the space for the compiled pattern.  */
  4279.   preg->buffer = 0;
  4280.   preg->allocated = 0;
  4281.   
  4282.   /* Don't bother to use a fastmap when searching.  This simplifies the
  4283.      REG_NEWLINE case: if we used a fastmap, we'd have to put all the
  4284.      characters after newlines into the fastmap.  This way, we just try
  4285.      every character.  */
  4286.   preg->fastmap = 0;
  4287.   
  4288.   if (cflags & REG_ICASE)
  4289.     {
  4290.       unsigned i;
  4291.       
  4292.       preg->translate = (char *) malloc (CHAR_SET_SIZE);
  4293.       if (preg->translate == NULL)
  4294.         return (int) REG_ESPACE;
  4295.  
  4296.       /* Map uppercase characters to corresponding lowercase ones.  */
  4297.       for (i = 0; i < CHAR_SET_SIZE; i++)
  4298.         preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
  4299.     }
  4300.   else
  4301.     preg->translate = NULL;
  4302.  
  4303.   /* If REG_NEWLINE is set, newlines are treated differently.  */
  4304.   if (cflags & REG_NEWLINE)
  4305.     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
  4306.       syntax &= ~RE_DOT_NEWLINE;
  4307.       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  4308.       /* It also changes the matching behavior.  */
  4309.       preg->newline_anchor = 1;
  4310.     }
  4311.   else
  4312.     preg->newline_anchor = 0;
  4313.  
  4314.   preg->no_sub = !!(cflags & REG_NOSUB);
  4315.  
  4316.   /* POSIX says a null character in the pattern terminates it, so we 
  4317.      can use strlen here in compiling the pattern.  */
  4318.   ret = regex_compile (pattern, strlen (pattern), syntax, preg);
  4319.   
  4320.   /* POSIX doesn't distinguish between an unmatched open-group and an
  4321.      unmatched close-group: both are REG_EPAREN.  */
  4322.   if (ret == REG_ERPAREN) ret = REG_EPAREN;
  4323.   
  4324.   return (int) ret;
  4325. }
  4326.  
  4327.  
  4328. /* regexec searches for a given pattern, specified by PREG, in the
  4329.    string STRING.
  4330.    
  4331.    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
  4332.    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
  4333.    least NMATCH elements, and we set them to the offsets of the
  4334.    corresponding matched substrings.
  4335.    
  4336.    EFLAGS specifies `execution flags' which affect matching: if
  4337.    REG_NOTBOL is set, then ^ does not match at the beginning of the
  4338.    string; if REG_NOTEOL is set, then $ does not match at the end.
  4339.    
  4340.    We return 0 if we find a match and REG_NOMATCH if not.  */
  4341.  
  4342. int
  4343. regexec (preg, string, nmatch, pmatch, eflags)
  4344.     const regex_t *preg;
  4345.     const char *string; 
  4346.     size_t nmatch; 
  4347.     regmatch_t pmatch[]; 
  4348.     int eflags;
  4349. {
  4350.   int ret;
  4351.   struct re_registers regs;
  4352.   regex_t private_preg;
  4353.   int len = strlen (string);
  4354.   boolean want_reg_info = !preg->no_sub && nmatch > 0;
  4355.  
  4356.   private_preg = *preg;
  4357.   
  4358.   private_preg.not_bol = !!(eflags & REG_NOTBOL);
  4359.   private_preg.not_eol = !!(eflags & REG_NOTEOL);
  4360.   
  4361.   /* The user has told us exactly how many registers to return
  4362.      information about, via `nmatch'.  We have to pass that on to the
  4363.      matching routines.  */
  4364.   private_preg.regs_allocated = REGS_FIXED;
  4365.   
  4366.   if (want_reg_info)
  4367.     {
  4368.       regs.num_regs = nmatch;
  4369.       regs.start = TALLOC (nmatch, regoff_t);
  4370.       regs.end = TALLOC (nmatch, regoff_t);
  4371.       if (regs.start == NULL || regs.end == NULL)
  4372.         return (int) REG_NOMATCH;
  4373.     }
  4374.  
  4375.   /* Perform the searching operation.  */
  4376.   ret = re_search (&private_preg, string, len,
  4377.                    /* start: */ 0, /* range: */ len,
  4378.                    want_reg_info ? ®s : (struct re_registers *) 0);
  4379.   
  4380.   /* Copy the register information to the POSIX structure.  */
  4381.   if (want_reg_info)
  4382.     {
  4383.       if (ret >= 0)
  4384.         {
  4385.           unsigned r;
  4386.  
  4387.           for (r = 0; r < nmatch; r++)
  4388.             {
  4389.               pmatch[r].rm_so = regs.start[r];
  4390.               pmatch[r].rm_eo = regs.end[r];
  4391.             }
  4392.         }
  4393.  
  4394.       /* If we needed the temporary register info, free the space now.  */
  4395.       free (regs.start);
  4396.       free (regs.end);
  4397.     }
  4398.  
  4399.   /* We want zero return to mean success, unlike `re_search'.  */
  4400.   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
  4401. }
  4402.  
  4403.  
  4404. /* Returns a message corresponding to an error code, ERRCODE, returned
  4405.    from either regcomp or regexec.   We don't use PREG here.  */
  4406.  
  4407. size_t
  4408. regerror (errcode, preg, errbuf, errbuf_size)
  4409.     int errcode;
  4410.     const regex_t *preg;
  4411.     char *errbuf;
  4412.     size_t errbuf_size;
  4413. {
  4414.   const char *msg;
  4415.   size_t msg_size;
  4416.  
  4417.   if (errcode < 0
  4418.       || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
  4419.     /* Only error codes returned by the rest of the code should be passed 
  4420.        to this routine.  If we are given anything else, or if other regex
  4421.        code generates an invalid error code, then the program has a bug.
  4422.        Dump core so we can fix it.  */
  4423.     abort ();
  4424.  
  4425.   msg = re_error_msg[errcode];
  4426.  
  4427.   /* POSIX doesn't require that we do anything in this case, but why
  4428.      not be nice.  */
  4429.   if (! msg)
  4430.     msg = "Success";
  4431.  
  4432.   msg_size = strlen (msg) + 1; /* Includes the null.  */
  4433.   
  4434.   if (errbuf_size != 0)
  4435.     {
  4436.       if (msg_size > errbuf_size)
  4437.         {
  4438.           strncpy (errbuf, msg, errbuf_size - 1);
  4439.           errbuf[errbuf_size - 1] = 0;
  4440.         }
  4441.       else
  4442.         strcpy (errbuf, msg);
  4443.     }
  4444.  
  4445.   return msg_size;
  4446. }
  4447.  
  4448.  
  4449. /* Free dynamically allocated space used by PREG.  */
  4450.  
  4451. void
  4452. regfree (preg)
  4453.     regex_t *preg;
  4454. {
  4455.   if (preg->buffer != NULL)
  4456.     free (preg->buffer);
  4457.   preg->buffer = NULL;
  4458.   
  4459.   preg->allocated = 0;
  4460.   preg->used = 0;
  4461.  
  4462.   if (preg->fastmap != NULL)
  4463.     free (preg->fastmap);
  4464.   preg->fastmap = NULL;
  4465.   preg->fastmap_accurate = 0;
  4466.  
  4467.   if (preg->translate != NULL)
  4468.     free (preg->translate);
  4469.   preg->translate = NULL;
  4470. }
  4471.  
  4472. #endif /* not emacs  */
  4473.  
  4474. /*
  4475. Local variables:
  4476. make-backup-files: t
  4477. version-control: t
  4478. trim-versions-without-asking: nil
  4479. End:
  4480. */
  4481.